Skip to content

Variational Guides

A variational guide is a family of distributions over the unobserved sites whose parameters optimization adjusts to approximate the posterior (Pyro Developers, n.d.-g; Blei et al., 2017; Hoffman et al., 2013). The guides live in submodules of quivers.inference.guides and share the Guide abstract base class and the LatentRegistry. They are AutoNormalGuide, AutoDeltaGuide, AutoMultivariateNormalGuide, AutoLowRankMultivariateNormalGuide, AutoLaplaceApproximation, AutoNormalizingFlow, AutoIAFGuide, AutoNeuralSplineGuide, AutoMixtureGuide, AutoGuideList, AutoStructured, and AmortizedGuide, which runs declared encoders on the data. Independent Normal guides represent marginal locations and scales, and covariance and flow guides also represent dependence.

quivers.inference re-exports every guide, and quivers.inference.guides adds the short names that Pyro uses (AutoNormal, AutoMultivariateNormal, AutoLowRankMVN, AutoDelta, AutoLaplace, AutoIAFNormal), each bound to the guide class it names, and the type aliases that configure AutoStructured.

The Laplace approximation uses a quadratic expansion around a mode (MacKay, 2003; Tierney and Kadane, 1986). The autoregressive flow implementations use masked networks (Germain et al., 2015). The invertible linear transform follows the construction used in Glow (Kingma and Dhariwal, 2018).

guides

Variational guide families.

Public surface (re-exported by the parent quivers.inference package): one ABC (Guide) plus a zoo of concrete Auto*Guide subclasses spanning the standard variational-family ladder from mean-field Normal to normalizing-flow stacks and hierarchical / mixture / structured guides.

Every concrete guide is built against a single quivers.inference.registry.LatentRegistry and obeys the shape contract documented on Guide.

Short-name aliases matching the Pyro AutoGuide naming (AutoNormal, AutoMultivariateNormal, AutoLowRankMVN, AutoDelta, AutoLaplace, AutoIAFNormal) are re-exported for users switching over from Pyro. The longer *Guide names remain the canonical quivers names.

AutoNormal module-attribute

AutoNormal = AutoNormalGuide

Pyro-style short name for AutoNormalGuide.

AutoMultivariateNormal module-attribute

AutoMultivariateNormal = AutoMultivariateNormalGuide

Pyro-style short name for AutoMultivariateNormalGuide.

AutoLowRankMVN module-attribute

Pyro-style short name for AutoLowRankMultivariateNormalGuide.

AutoDelta module-attribute

AutoDelta = AutoDeltaGuide

Pyro-style short name for AutoDeltaGuide.

AutoLaplace module-attribute

Pyro-style short name for AutoLaplaceApproximation.

AutoIAFNormal module-attribute

AutoIAFNormal = AutoIAFGuide

Pyro-style short name for AutoIAFGuide.

ConditionalSpec

ConditionalSpec = str | Mapping[str, str]

The per-site marginal families of an AutoStructured guide: one family name ("delta", "normal", or "mvn") for every site, or a mapping from site name to family name.

DependencyKind

DependencyKind = str | Callable[[Tensor], Tensor]

One dependency edge of an AutoStructured guide: the string "linear" for a learned linear shift, or a callable mapping the parent's unconstrained flat draw to a shift on the child's unconstrained flat location.

DependencySpec

DependencySpec = Mapping[str, Mapping[str, DependencyKind]]

The dependency edges of an AutoStructured guide, keyed first by child site and then by parent site.

AmortizedGuide

AmortizedGuide(model: MonadicProgram, observed_names: set[str], encoders: Mapping[str, tuple[ContinuousMorphism, str]], *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None)

Bases: Guide

Variational guide that runs encoders on the data.

PARAMETER DESCRIPTION
model

The model.

TYPE: MonadicProgram

observed_names

The observed site names, for a registry read off the model.

TYPE: set[str]

encoders

For each latent site the guide covers, the encoder and the name of the datum (an observation or a host datum) it reads. Other latent sites are left to another guide, composed with this one in an AutoGuideList.

TYPE: Mapping[str, tuple[ContinuousMorphism, str]]

x

Keyword-only. A program input at which to build the registry from a run (Guide.build_registry).

TYPE: Tensor | None DEFAULT: None

observations

Keyword-only. The data of that run; when given, the guide also observes them (observe).

TYPE: dict[str, Tensor] | None DEFAULT: None

RAISES DESCRIPTION
ValueError

If encoders is empty, names a site that is not a latent of the registry, or binds an encoder whose support is neither the site's nor the real line (for a site with another support), or whose event size does not match the site's coordinates.

TypeError

If an encoder is not a ContinuousMorphism.

Source code in src/quivers/inference/guides/amortized.py
def __init__(
    self,
    model: MonadicProgram,
    observed_names: set[str],
    encoders: Mapping[str, tuple[ContinuousMorphism, str]],
    *,
    x: torch.Tensor | None = None,
    observations: dict[str, torch.Tensor] | None = None,
) -> None:
    super().__init__()
    if not encoders:
        raise ValueError("AmortizedGuide: encoders must bind at least one site")
    self._registry = self.build_registry(
        model, observed_names, x=x, observations=observations
    )
    unknown = sorted(name for name in encoders if name not in self._registry)
    if unknown:
        raise ValueError(
            f"AmortizedGuide: {unknown} are not latent sites of the model; its "
            f"latent sites are {list(self._registry.names)}"
        )
    self._bindings: dict[str, _Binding] = {}
    modules: list[ContinuousMorphism] = []
    for name, (encoder, datum) in encoders.items():
        if not isinstance(encoder, ContinuousMorphism):
            raise TypeError(
                f"AmortizedGuide: the encoder of {name!r} is a "
                f"{type(encoder).__name__}, not a ContinuousMorphism"
            )
        self._bindings[name] = self._bind(self._registry[name], encoder, datum)
        modules.append(encoder)
    # The encoders' weights are the guide's variational parameters.
    self.encoders = nn.ModuleList(modules)
    self._data: dict[str, torch.Tensor] | None = None
    if observations is not None:
        self.observe(observations)

latent_names property

latent_names: list[str]

The sites the encoders cover.

uncovered_sites property

uncovered_sites: tuple[str, ...]

The model's latent sites no encoder covers; another guide in an AutoGuideList must cover them.

observe

observe(observations: Mapping[str, Tensor]) -> None

Take the data the encoders read.

Every objective calls this with the observations of the step it evaluates; call it directly before sampling the guide on other data, such as held-out data.

PARAMETER DESCRIPTION
observations

Observed values and host data.

TYPE: Mapping[str, Tensor]

RAISES DESCRIPTION
ValueError

If a datum an encoder reads is missing, or an encoder's density is not exact at it.

Source code in src/quivers/inference/guides/amortized.py
def observe(self, observations: Mapping[str, torch.Tensor]) -> None:
    """Take the data the encoders read.

    Every objective calls this with the observations of the step it
    evaluates; call it directly before sampling the guide on other
    data, such as held-out data.

    Parameters
    ----------
    observations : Mapping[str, torch.Tensor]
        Observed values and host data.

    Raises
    ------
    ValueError
        If a datum an encoder reads is missing, or an encoder's
        density is not exact at it.
    """
    missing = sorted({b.datum for b in self._bindings.values()} - set(observations))
    if missing:
        raise ValueError(
            f"AmortizedGuide: the encoders read {missing}, which the "
            "observations do not supply"
        )
    data = {
        b.datum: torch.as_tensor(observations[b.datum])
        for b in self._bindings.values()
    }
    for binding in self._bindings.values():
        rows, _ = self._rows(binding, data[binding.datum])
        _check_exact_density(binding.encoder, rows[:1])
    self._data = data

rsample

rsample(x: Tensor) -> dict[str, Tensor]

Draw every bound site from its encoder applied to its datum.

PARAMETER DESCRIPTION
x

The program input; its rows are the runs.

TYPE: Tensor

RETURNS DESCRIPTION
dict[str, Tensor]

Trace-side values: (B, *constrained_shape) for a site drawn once per run, the plate's rows (behind the run axis when the datum has one) for a plate site.

Source code in src/quivers/inference/guides/amortized.py
def rsample(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
    """Draw every bound site from its encoder applied to its datum.

    Parameters
    ----------
    x : torch.Tensor
        The program input; its rows are the runs.

    Returns
    -------
    dict[str, torch.Tensor]
        Trace-side values: ``(B, *constrained_shape)`` for a site
        drawn once per run, the plate's rows (behind the run axis
        when the datum has one) for a plate site.
    """
    batch = int(x.shape[0])
    out: dict[str, torch.Tensor] = {}
    for name, binding in self._bindings.items():
        rows, leading = self._datum(binding, batch)
        draws = binding.encoder.rsample(rows).reshape(*leading, binding.width)
        out[name] = self._to_site(binding, draws)
    return out

log_prob

log_prob(x: Tensor, sites: dict[str, Tensor]) -> Tensor

The guide's log-density of site values, per run.

For a site reached through the bijector :math:T, :math:\log q(v) = \log e(T^{-1}(v) \mid y) + \log |\det J_{T^{-1}}(v)|; otherwise :math:\log e(v \mid y). Each site's value is read per run (LatentSite.align_runs), and the encoder rows a run reads are its own rows of the datum, or the rows every run shares when the datum has no run axis. A plate site's rows add up within a run; under a subsample block only the subset's rows do, times the plate's size over the subset's.

PARAMETER DESCRIPTION
x

The program input.

TYPE: Tensor

sites

Trace-side values of the bound sites, each one per run or one the runs share (Guide.log_prob).

TYPE: dict[str, Tensor]

RETURNS DESCRIPTION
Tensor

Shape (B,).

RAISES DESCRIPTION
KeyError

If a bound site is missing from sites.

ValueError

If a value is neither one per run nor one the runs share.

Source code in src/quivers/inference/guides/amortized.py
def log_prob(self, x: torch.Tensor, sites: dict[str, torch.Tensor]) -> torch.Tensor:
    """The guide's log-density of site values, per run.

    For a site reached through the bijector :math:`T`,
    :math:`\\log q(v) = \\log e(T^{-1}(v) \\mid y) + \\log
    |\\det J_{T^{-1}}(v)|`; otherwise :math:`\\log e(v \\mid y)`.
    Each site's value is read per run (`LatentSite.align_runs`), and
    the encoder rows a run reads are its own rows of the datum, or
    the rows every run shares when the datum has no run axis. A
    plate site's rows add up within a run; under a
    [`subsample`][quivers.effects.subsample] block only the subset's
    rows do, times the plate's size over the subset's.

    Parameters
    ----------
    x : torch.Tensor
        The program input.
    sites : dict[str, torch.Tensor]
        Trace-side values of the bound sites, each one per run or one
        the runs share (`Guide.log_prob`).

    Returns
    -------
    torch.Tensor
        Shape ``(B,)``.

    Raises
    ------
    KeyError
        If a bound site is missing from ``sites``.
    ValueError
        If a value is neither one per run nor one the runs share.
    """
    runs = int(x.shape[0])
    total = torch.zeros(runs, device=x.device)
    for name, binding in self._bindings.items():
        if name not in sites:
            raise KeyError(f"AmortizedGuide.log_prob: missing site {name!r}")
        site = binding.site
        elements = site.plate_index_size if site.is_plate else 1
        domain = _event_shape(binding.encoder.domain)
        codomain = _event_shape(binding.encoder.codomain)
        rows, _ = self._datum(binding, runs)
        rows = rows.reshape(-1, elements, *domain).expand(runs, elements, *domain)
        if binding.through_bijector:
            z, log_det = site.unconstrain_runs(sites[name], runs)
            log_det = log_det.reshape(runs, elements)
        else:
            z = site.align_runs(sites[name], runs)
            log_det = z.new_zeros(runs, elements)
        log_q = binding.encoder.log_prob(
            rows.reshape(runs * elements, *domain),
            z.reshape(runs * elements, *codomain),
        ).reshape(runs, elements)
        terms = log_q + log_det
        if site.is_plate:
            total = total + self._plate_run_totals(site, terms)
        else:
            total = total + terms.reshape(runs)
    return total

AutoGuideList

AutoGuideList(parts: dict[str, Guide])

Bases: Guide

A block-composed variational guide.

PARAMETER DESCRIPTION
parts

Named subguides, each covering a disjoint set of latent site names. Keys are labels used for parameter-namespacing and error messages; values are any Guide subclass. Every guide's Guide.latent_names must be pairwise disjoint from every other's.

TYPE: dict[str, Guide]

Source code in src/quivers/inference/guides/auto_guide_list.py
def __init__(self, parts: dict[str, Guide]) -> None:
    super().__init__()
    if len(parts) == 0:
        raise ValueError("AutoGuideList: parts must be non-empty")

    seen: dict[str, str] = {}
    for label, part in parts.items():
        for name in part.latent_names:
            if name in seen:
                raise ValueError(
                    f"AutoGuideList: latent {name!r} appears in "
                    f"both part {seen[name]!r} and part {label!r}; "
                    f"parts must cover disjoint site sets"
                )
            seen[name] = label
    self._parts_dict: dict[str, Guide] = dict(parts)
    self.parts = nn.ModuleDict(parts)
    self._latent_names: list[str] = list(seen.keys())
    self._site_to_part: dict[str, str] = seen

part_labels property

part_labels: tuple[str, ...]

Labels of the sub-guides, in declaration order.

registry property

registry

The list-guide has no single fused registry; downstream code that needs one should walk part_labels and pull each sub-guide's Guide.registry directly.

part

part(label: str) -> Guide

Look up a sub-guide by label.

Source code in src/quivers/inference/guides/auto_guide_list.py
def part(self, label: str) -> Guide:
    """Look up a sub-guide by label."""
    if label not in self._parts_dict:
        raise KeyError(
            f"AutoGuideList: no part labelled {label!r}; "
            f"available: {tuple(self._parts_dict)!r}"
        )
    return self._parts_dict[label]

observe

observe(observations: Mapping[str, Tensor]) -> None

Forward the step's data to every part.

PARAMETER DESCRIPTION
observations

Observed values and host data.

TYPE: Mapping[str, Tensor]

Source code in src/quivers/inference/guides/auto_guide_list.py
def observe(self, observations: Mapping[str, torch.Tensor]) -> None:
    """Forward the step's data to every part.

    Parameters
    ----------
    observations : Mapping[str, torch.Tensor]
        Observed values and host data.
    """
    for part in self._parts_dict.values():
        part.observe(observations)

rsample

rsample(x: Tensor) -> dict[str, Tensor]

Concatenate per-part reparameterized draws.

Source code in src/quivers/inference/guides/auto_guide_list.py
def rsample(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
    """Concatenate per-part reparameterized draws."""
    result: dict[str, torch.Tensor] = {}
    for part in self._parts_dict.values():
        part_sample = part.rsample(x)
        for name, tensor in part_sample.items():
            result[name] = tensor
    return result

rsample_strata

rsample_strata(x: Tensor) -> tuple[GuideDraw, ...]

Product of the parts' strata.

The parts are independent, so the joint guide's strata are the Cartesian product of the parts' strata: each joint draw merges one draw per part and carries the sums of the parts' log-weights and log-densities. A part that is an AutoMixtureGuide thus has its components enumerated inside the list guide, and an AutoDAIS part contributes the density of its own trajectory.

PARAMETER DESCRIPTION
x

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

TYPE: Tensor

RETURNS DESCRIPTION
tuple[GuideDraw, ...]

S merged draws, where S is the product of the parts' stratum counts.

Source code in src/quivers/inference/guides/auto_guide_list.py
def rsample_strata(self, x: torch.Tensor) -> tuple[GuideDraw, ...]:
    """Product of the parts' strata.

    The parts are independent, so the joint guide's strata are the
    Cartesian product of the parts' strata: each joint draw merges
    one draw per part and carries the sums of the parts'
    log-weights and log-densities. A part that is an
    `AutoMixtureGuide` thus has its components enumerated inside
    the list guide, and an `AutoDAIS` part contributes the density
    of its own trajectory.

    Parameters
    ----------
    x : torch.Tensor
        Program input. Shape ``(batch, ...)``.

    Returns
    -------
    tuple[GuideDraw, ...]
        ``S`` merged draws, where ``S`` is the product of the parts'
        stratum counts.
    """
    joint: list[GuideDraw] | None = None
    for part in self._parts_dict.values():
        part_draws = part.rsample_strata(x)
        if joint is None:
            joint = list(part_draws)
            continue
        joint = [
            GuideDraw(
                sites={**prefix.sites, **draw.sites},
                log_density=prefix.log_density + draw.log_density,
                log_weight=prefix.log_weight + draw.log_weight,
            )
            for prefix in joint
            for draw in part_draws
        ]
    assert joint is not None
    return tuple(joint)

log_prob

log_prob(x: Tensor, sites: dict[str, Tensor]) -> Tensor

Sum per-part log-densities.

Each sub-guide receives only the site keys it owns; a missing key raises KeyError in the sub-guide.

Source code in src/quivers/inference/guides/auto_guide_list.py
def log_prob(
    self,
    x: torch.Tensor,
    sites: dict[str, torch.Tensor],
) -> torch.Tensor:
    """Sum per-part log-densities.

    Each sub-guide receives only the site keys it owns; a
    missing key raises `KeyError` in the sub-guide.
    """
    total: torch.Tensor | None = None
    for label, part in self._parts_dict.items():
        part_sites = {
            name: sites[name] for name in part.latent_names if name in sites
        }
        missing = [n for n in part.latent_names if n not in sites]
        if missing:
            raise KeyError(
                f"AutoGuideList.log_prob: part {label!r} needs "
                f"sites {missing!r} but they are not in the input"
            )
        contribution = part.log_prob(x, part_sites)
        total = contribution if total is None else total + contribution
    assert total is not None
    return total

AutoStructured

AutoStructured(model: MonadicProgram, observed_names: set[str], conditionals: ConditionalSpec, dependencies: DependencySpec | None = None, init_scale: float = 0.1, *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None)

Bases: Guide

Per-site / per-edge structured variational guide.

PARAMETER DESCRIPTION
model

Generative model to build a guide for.

TYPE: MonadicProgram

observed_names

Variable names treated as observations.

TYPE: set[str]

x

Keyword-only. A program input at which to build the latent registry from a run, required for a program that scans or calls a program that draws, whose latent sites depend on its input.

TYPE: Tensor | None DEFAULT: None

observations

Keyword-only. The observed values and host data of that run.

TYPE: dict[str, Tensor] | None DEFAULT: None

conditionals

Per-site marginal-family choice. A single string sets every site to the same family. A dict maps site name to family. Allowed families:

  • "delta": Dirac mass at a learnable location (analogous to AutoDeltaGuide).
  • "normal": independent-Normal marginal.
  • "mvn": the site is part of a joint multivariate Normal block. Every "mvn" site shares one Cholesky factor sized to the sum of every "mvn" site's flat length. This matches Pyro's convention.

TYPE: str or dict[str, str]

dependencies

Directed edges. dependencies[child][parent] is either the string "linear" (build a _LinearDependency from the parent's unconstrained flat draw to a shift on the child's unconstrained flat location) or a user-supplied callable with the same signature, mapping one draw of shape (parent_flat,) to one shift of shape (child_flat,). The guide applies every dependency to one run's draw at a time through torch.func.vmap, so a callable must be built from torch operations that vmap supports. Every dependency must reference a site strictly upstream in declaration order.

TYPE: dict[str, dict[str, DependencyKind]] or None DEFAULT: None

init_scale

Initial scale of every "normal" and "mvn" marginal. Default 0.1.

TYPE: float DEFAULT: 0.1

Source code in src/quivers/inference/guides/auto_structured.py
def __init__(
    self,
    model: MonadicProgram,
    observed_names: set[str],
    conditionals: ConditionalSpec,
    dependencies: DependencySpec | None = None,
    init_scale: float = 0.1,
    *,
    x: torch.Tensor | None = None,
    observations: dict[str, torch.Tensor] | None = None,
) -> None:
    super().__init__()
    self._registry = self.build_registry(
        model, observed_names, x=x, observations=observations
    )

    # --- Normalise conditionals ---
    site_names = list(self._registry.names)
    if isinstance(conditionals, str):
        if conditionals not in _ALLOWED_CONDITIONALS:
            raise ValueError(
                f"AutoStructured: conditional {conditionals!r} "
                f"not in {sorted(_ALLOWED_CONDITIONALS)!r}"
            )
        resolved: dict[str, str] = {n: conditionals for n in site_names}
    else:
        resolved = {}
        for n in site_names:
            if n not in conditionals:
                raise ValueError(
                    f"AutoStructured: conditionals dict has no "
                    f"entry for latent site {n!r}"
                )
            choice = conditionals[n]
            if choice not in _ALLOWED_CONDITIONALS:
                raise ValueError(
                    f"AutoStructured: conditional {choice!r} for "
                    f"site {n!r} not in "
                    f"{sorted(_ALLOWED_CONDITIONALS)!r}"
                )
            resolved[n] = choice
    self._conditionals: dict[str, str] = resolved

    # --- Register per-site location + scale parameters ---
    init_log_scale = float(torch.tensor(init_scale).log().item())
    for name in site_names:
        site = self._registry.sites[name]
        self.register_parameter(
            f"loc_{name}",
            nn.Parameter(torch.zeros(site.unconstrained_shape)),
        )
        if resolved[name] == "normal":
            self.register_parameter(
                f"log_scale_{name}",
                nn.Parameter(torch.full(site.unconstrained_shape, init_log_scale)),
            )
        # "delta" has no scale.  "mvn" scale is shared and set below.

    # --- Set up the shared MVN block, if any ---
    mvn_names: list[str] = [n for n in site_names if resolved[n] == "mvn"]
    self._mvn_names: list[str] = mvn_names
    self._mvn_offsets: dict[str, int] = {}
    cursor = 0
    for n in mvn_names:
        self._mvn_offsets[n] = cursor
        cursor += _site_flat_length(self._registry.sites[n])
    self._mvn_total: int = cursor
    if mvn_names:
        init_diag = torch.full((self._mvn_total,), float(init_scale))
        init_diag_raw = torch.log(torch.expm1(init_diag.clamp(min=1e-6)))
        self.mvn_scale_diag_raw = nn.Parameter(init_diag_raw)
        self.mvn_scale_offdiag = nn.Parameter(
            torch.zeros(self._mvn_total, self._mvn_total)
        )

    # --- Validate + register dependencies ---
    deps = dependencies or {}
    name_order: dict[str, int] = {n: i for i, n in enumerate(site_names)}
    dep_modules: dict[str, nn.ModuleDict] = {}
    for child, parents in deps.items():
        if child not in name_order:
            raise ValueError(
                f"AutoStructured: dependency child {child!r} is not a latent site"
            )
        child_flat = _site_flat_length(self._registry.sites[child])
        per_parent = nn.ModuleDict()
        for parent, kind in parents.items():
            if parent not in name_order:
                raise ValueError(
                    f"AutoStructured: dependency parent {parent!r} "
                    f"(for child {child!r}) is not a latent site"
                )
            if name_order[parent] >= name_order[child]:
                raise ValueError(
                    f"AutoStructured: dependency {parent!r} -> "
                    f"{child!r} is not strictly upstream in "
                    f"declaration order"
                )
            parent_flat = _site_flat_length(self._registry.sites[parent])
            if kind == "linear":
                per_parent[parent] = _LinearDependency(
                    parent_flat=parent_flat, child_flat=child_flat
                )
            elif callable(kind):
                per_parent[parent] = _CallableDependency(kind)
            else:
                raise ValueError(
                    f"AutoStructured: dependency kind {kind!r} "
                    f"for edge {parent!r} -> {child!r} must be "
                    f"either the string 'linear' or a callable"
                )
        dep_modules[child] = per_parent
    self.deps = nn.ModuleDict(dep_modules)
    self._dependency_maps: dict[str, dict[str, nn.Module]] = {
        child: dict(per_parent.items()) for child, per_parent in dep_modules.items()
    }
    self._dep_spec: dict[str, dict[str, DependencyKind]] = {
        child: dict(parents) for child, parents in deps.items()
    }

conditionals property

conditionals: dict[str, str]

Per-site marginal family, as resolved at construction.

dependencies property

dependencies: dict[str, dict[str, DependencyKind]]

The declared per-edge dependence structure.

rsample

rsample(x: Tensor) -> dict[str, Tensor]

Ancestral reparameterized draw, one shared by every run.

PARAMETER DESCRIPTION
x

Program input; its leading axis has one row per run.

TYPE: Tensor

RETURNS DESCRIPTION
dict[str, Tensor]

Per-site constrained values: (B, *constrained_shape) for a site that is not plated, the same draw in every run, and LatentSite.constrained_shape for a plate site.

RAISES DESCRIPTION
RuntimeError

If a site has a conditional kind outside the allowed ones.

Source code in src/quivers/inference/guides/auto_structured.py
def rsample(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
    """Ancestral reparameterized draw, one shared by every run.

    Parameters
    ----------
    x : torch.Tensor
        Program input; its leading axis has one row per run.

    Returns
    -------
    dict[str, torch.Tensor]
        Per-site constrained values: ``(B, *constrained_shape)`` for
        a site that is not plated, the same draw in every run, and
        `LatentSite.constrained_shape` for a plate site.

    Raises
    ------
    RuntimeError
        If a site has a conditional kind outside the allowed ones.
    """
    batch = x.shape[0]
    # First sample the shared MVN block (if any) in flat form.
    if self._mvn_names:
        mvn_flat: dict[str, torch.Tensor] = self._sample_mvn_block()
    else:
        mvn_flat = {}
    # Then walk sites in declaration order, sampling each per its
    # marginal family, offsetting the location by every incoming
    # dependency's contribution. The draw is one run's, held behind
    # a run axis of one so the dependencies see it as `log_prob`
    # does.
    result: dict[str, torch.Tensor] = {}
    z_flat_by_site: dict[str, torch.Tensor] = {}
    for site in self._registry.sites.values():
        name = site.name
        kind = self._conditionals[name]
        shift = self._shift(site, z_flat_by_site, 1)
        shifted_loc = self._loc(name).reshape(1, -1) + shift
        if kind == "delta":
            z_flat = shifted_loc
        elif kind == "normal":
            scale = self._normal_scale(name).reshape(1, -1)
            z_flat = D.Normal(shifted_loc, scale).rsample()
        elif kind == "mvn":
            z_flat = mvn_flat[name].unsqueeze(0) + shift
        else:
            raise RuntimeError(
                f"AutoStructured.rsample: unhandled conditional kind {kind!r}"
            )
        z_flat_by_site[name] = z_flat
        result[name] = _push_through_bijector(site, z_flat[0], batch)
    return result

log_prob

log_prob(x: Tensor, sites: dict[str, Tensor]) -> Tensor

Pushforward log-density of each run's constrained values.

For run b, every site's value is inverted through its bijector (LatentRegistry.unconstrain_runs), each "normal" site is scored under its Normal at its location shifted by run b's parent draws, the "mvn" sites are scored jointly, and every site's inverse-bijector term at run b's value is added. A "delta" site contributes its bijector term only.

PARAMETER DESCRIPTION
x

Program input; its leading axis has one row per run.

TYPE: Tensor

sites

Constrained values of every latent site, each one per run or one the runs share (Guide.log_prob).

TYPE: dict[str, Tensor]

RETURNS DESCRIPTION
Tensor

Shape (B,), one log density per run.

RAISES DESCRIPTION
KeyError

If a latent site is missing from sites.

ValueError

If a value is neither one per run nor one the runs share.

Source code in src/quivers/inference/guides/auto_structured.py
def log_prob(
    self,
    x: torch.Tensor,
    sites: dict[str, torch.Tensor],
) -> torch.Tensor:
    """Pushforward log-density of each run's constrained values.

    For run ``b``, every site's value is inverted through its
    bijector (`LatentRegistry.unconstrain_runs`), each ``"normal"``
    site is scored under its Normal at its location shifted by run
    ``b``'s parent draws, the ``"mvn"`` sites are scored jointly, and
    every site's inverse-bijector term at run ``b``'s value is
    added. A ``"delta"`` site contributes its bijector term only.

    Parameters
    ----------
    x : torch.Tensor
        Program input; its leading axis has one row per run.
    sites : dict[str, torch.Tensor]
        Constrained values of every latent site, each one per run or
        one the runs share (`Guide.log_prob`).

    Returns
    -------
    torch.Tensor
        Shape ``(B,)``, one log density per run.

    Raises
    ------
    KeyError
        If a latent site is missing from ``sites``.
    ValueError
        If a value is neither one per run nor one the runs share.
    """
    runs = int(x.shape[0])
    coordinates = self._registry.unconstrain_runs(sites, runs)
    z_flat_by_site = {
        site.name: coordinates.unconstrained[site.name].reshape(
            runs, _site_flat_length(site)
        )
        for site in self._registry.sites.values()
    }
    total = coordinates.total_log_abs_det()
    joint_loc_parts: list[torch.Tensor] = []
    joint_z_parts: list[torch.Tensor] = []
    for site in self._registry.sites.values():
        name = site.name
        kind = self._conditionals[name]
        if kind == "delta":
            continue
        shifted_loc = self._loc(name).reshape(1, -1) + self._shift(
            site, z_flat_by_site, runs
        )
        if kind == "normal":
            scale = self._normal_scale(name).reshape(-1)
            log_q = D.Normal(shifted_loc, scale).log_prob(z_flat_by_site[name])
            total = total + log_q.sum(-1)
        else:
            # "mvn" sites are scored jointly below.
            joint_loc_parts.append(shifted_loc)
            joint_z_parts.append(z_flat_by_site[name])
    if joint_loc_parts:
        dist = D.MultivariateNormal(
            torch.cat(joint_loc_parts, dim=-1), scale_tril=self._mvn_scale_tril()
        )
        total = total + dist.log_prob(torch.cat(joint_z_parts, dim=-1))
    return total

Guide

Bases: Module, ABC

Abstract variational guide.

Subclasses MUST implement rsample and log_prob and expose latent_names. They MAY override registry if they construct their registry lazily, but the default implementation expects self._registry to be set in __init__.

scores_subsampled_rows class-attribute

scores_subsampled_rows: bool = False

Whether log_prob scores a latent in a subsampled plate at the subset's rows, scaled as the model's sites are. A guide whose density does not split over a plate's rows leaves it False and refuses such a latent through check_subsampling.

registry property

registry: LatentRegistry

The LatentRegistry this guide was built against.

latent_names abstractmethod property

latent_names: list[str]

Names of latent variables this guide covers.

check_subsampling

check_subsampling() -> None

Refuse a latent in a subsampled plate this guide cannot score by rows.

Under a subsample block the model scores a plate's latents at the subset's rows, scaled; the guide's density must match, or the objective is not an unbiased estimate of the full one. A guide that scores rows declares scores_subsampled_rows.

RAISES DESCRIPTION
ValueError

If a subsampled plate holds one of the guide's latents and the guide does not score a plate's rows separately.

Source code in src/quivers/inference/guides/base.py
def check_subsampling(self) -> None:
    """Refuse a latent in a subsampled plate this guide cannot score by rows.

    Under a [`subsample`][quivers.effects.subsample] block the model
    scores a plate's latents at the subset's rows, scaled; the
    guide's density must match, or the objective is not an unbiased
    estimate of the full one. A guide that scores rows declares
    `scores_subsampled_rows`.

    Raises
    ------
    ValueError
        If a subsampled plate holds one of the guide's latents and
        the guide does not score a plate's rows separately.
    """
    subsets = active_subsets()
    if not subsets or self.scores_subsampled_rows:
        return
    plates = self.registry.model.site_plates
    for name in self.registry.names:
        axes = plates.get(name.split("@")[0], ())
        held = sorted(plate for plate, _ in axes if plate in subsets)
        if held:
            raise ValueError(
                f"{type(self).__name__} cannot score latent {name!r} in the "
                f"subsampled plate {held[0]!r} at the subset's rows, since "
                "its density does not split over the plate; use "
                "AutoNormalGuide, AmortizedGuide or AutoDeltaGuide for the "
                "plate's latents, or leave the plate unsubsampled"
            )

build_registry classmethod

build_registry(model: MonadicProgram, observed_names: set[str] | frozenset[str], *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None) -> LatentRegistry

Build the latent registry a guide is constructed against.

PARAMETER DESCRIPTION
model

The model.

TYPE: MonadicProgram

observed_names

The names observed, for a registry read off the model's steps.

TYPE: set[str] | frozenset[str]

x

A program input. When given, the registry is built from a run of the model at x and observations with LatentRegistry.from_trace, so every site the run reaches is a latent, every position of a scan included; the run draws from a forked stream, leaving Torch's global RNG as it was. Required for a program that scans or calls a program that draws.

TYPE: Tensor | None DEFAULT: None

observations

The observed values and host data of that run.

TYPE: dict[str, Tensor] | None DEFAULT: None

RETURNS DESCRIPTION
LatentRegistry

The registry.

Source code in src/quivers/inference/guides/base.py
@classmethod
def build_registry(
    cls,
    model: MonadicProgram,
    observed_names: set[str] | frozenset[str],
    *,
    x: torch.Tensor | None = None,
    observations: dict[str, torch.Tensor] | None = None,
) -> LatentRegistry:
    """Build the latent registry a guide is constructed against.

    Parameters
    ----------
    model : MonadicProgram
        The model.
    observed_names : set[str] | frozenset[str]
        The names observed, for a registry read off the model's
        steps.
    x : torch.Tensor | None
        A program input. When given, the registry is built from a
        run of the model at ``x`` and ``observations`` with
        `LatentRegistry.from_trace`, so every site the run reaches
        is a latent, every position of a scan included; the run
        draws from a forked stream, leaving Torch's global RNG as it
        was. Required for a program that scans or calls a program
        that draws.
    observations : dict[str, torch.Tensor] | None
        The observed values and host data of that run.

    Returns
    -------
    LatentRegistry
        The registry.
    """
    if x is None:
        return LatentRegistry.from_model(model, observed_names)
    with torch.random.fork_rng(devices=[]), latent_structure_recording():
        recorded = _trace.trace(model, x, observations=dict(observations or {}))
    return LatentRegistry.from_trace(model, recorded)

observe

observe(observations: Mapping[str, Tensor]) -> None

Receive the data of the step about to sample the guide.

Every objective calls this with its step's observations and host data before it draws from the guide, so a guide that reads the data (an AmortizedGuide) samples the posterior of the data the step scores. A guide whose parameters do not depend on the data ignores them, as this base implementation does.

PARAMETER DESCRIPTION
observations

Observed values and host data.

TYPE: Mapping[str, Tensor]

Source code in src/quivers/inference/guides/base.py
def observe(self, observations: Mapping[str, torch.Tensor]) -> None:
    """Receive the data of the step about to sample the guide.

    Every objective calls this with its step's observations and host
    data before it draws from the guide, so a guide that reads the
    data (an `AmortizedGuide`) samples the posterior of the data the
    step scores. A guide whose parameters do not depend on the data
    ignores them, as this base implementation does.

    Parameters
    ----------
    observations : Mapping[str, torch.Tensor]
        Observed values and host data.
    """
    del observations

rsample abstractmethod

rsample(x: Tensor) -> dict[str, Tensor]

Reparameterized sample from :math:q_\phi(z \mid x).

PARAMETER DESCRIPTION
x

Program input. Shape (batch, ...). Used only for its batch dim and device; the variational parameters are stored on the guide itself.

TYPE: Tensor

RETURNS DESCRIPTION
dict[str, Tensor]

Per-site constrained samples shaped to match the model's trace-side convention.

Source code in src/quivers/inference/guides/base.py
@abstractmethod
def rsample(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
    """Reparameterized sample from :math:`q_\\phi(z \\mid x)`.

    Parameters
    ----------
    x : torch.Tensor
        Program input. Shape ``(batch, ...)``. Used only for
        its batch dim and device; the variational parameters
        are stored on the guide itself.

    Returns
    -------
    dict[str, torch.Tensor]
        Per-site constrained samples shaped to match the
        model's trace-side convention.
    """
    ...

rsample_strata

rsample_strata(x: Tensor) -> tuple[GuideDraw, ...]

Weighted reparameterized draws from :math:q_\phi(z \mid x).

Returns one GuideDraw per stratum :math:s, with log-weight :math:\log \omega_s and a draw :math:z_s \sim q_s, such that the strata partition the guide's density, :math:q_\phi = \sum_s \omega_s\, q_s with :math:\sum_s \omega_s = 1. Thus :math:\sum_s \omega_s f(z_s) is an unbiased estimate of :math:\mathbb{E}_{q_\phi}[f(z)] for every f, and :math:\sum_s \omega_s\, p(z_s) / q_\phi(z_s) is an unbiased estimate of :math:\int p. Each draw carries the guide log-density the objectives pair it with. Gradients reach the variational parameters through the reparameterized draws, the densities, and the log-weights.

The default returns a single draw from rsample with log-weight zero, scored by log_prob. A guide with a discrete choice inside its sampler (such as AutoMixtureGuide) overrides it to enumerate that choice; a guide without a density at arbitrary points (such as AutoDAIS) overrides it to return the density of the path that produced the draw.

PARAMETER DESCRIPTION
x

Program input, as for rsample.

TYPE: Tensor

RETURNS DESCRIPTION
tuple[GuideDraw, ...]

The S weighted draws; their log-weights have logsumexp == 0.

Source code in src/quivers/inference/guides/base.py
def rsample_strata(self, x: torch.Tensor) -> tuple[GuideDraw, ...]:
    """Weighted reparameterized draws from :math:`q_\\phi(z \\mid x)`.

    Returns one `GuideDraw` per stratum :math:`s`, with log-weight
    :math:`\\log \\omega_s` and a draw :math:`z_s \\sim q_s`, such
    that the strata partition the guide's density,
    :math:`q_\\phi = \\sum_s \\omega_s\\, q_s` with
    :math:`\\sum_s \\omega_s = 1`. Thus
    :math:`\\sum_s \\omega_s f(z_s)` is an unbiased estimate of
    :math:`\\mathbb{E}_{q_\\phi}[f(z)]` for every ``f``, and
    :math:`\\sum_s \\omega_s\\, p(z_s) / q_\\phi(z_s)` is an
    unbiased estimate of :math:`\\int p`. Each draw carries the guide
    log-density the objectives pair it with. Gradients reach the
    variational parameters through the reparameterized draws, the
    densities, and the log-weights.

    The default returns a single draw from `rsample` with log-weight
    zero, scored by `log_prob`. A guide with a discrete choice inside
    its sampler (such as `AutoMixtureGuide`) overrides it to
    enumerate that choice; a guide without a density at arbitrary
    points (such as `AutoDAIS`) overrides it to return the density
    of the path that produced the draw.

    Parameters
    ----------
    x : torch.Tensor
        Program input, as for `rsample`.

    Returns
    -------
    tuple[GuideDraw, ...]
        The ``S`` weighted draws; their log-weights have
        ``logsumexp == 0``.
    """
    sites = self.rsample(x)
    log_density = self.log_prob(x, sites)
    return (
        GuideDraw(
            sites=sites,
            log_density=log_density,
            log_weight=torch.zeros((), device=x.device, dtype=log_density.dtype),
        ),
    )

log_prob abstractmethod

log_prob(x: Tensor, sites: dict[str, Tensor]) -> Tensor

Log density of sites under :math:q_\phi(z \mid x), run by run.

An input x of B rows is B independent runs of the program, and the guide's law :math:q_\phi is a law over the latents of one run. The value of each site in sites either has a leading run axis, shape (B, *constrained_shape), with run b's value at index b, or has shape LatentSite.constrained_shape and is one value every run shares; LatentSite.align_runs states the rule, and any other shape is refused. Entry b of the result is :math:\log q_\phi(v_b), the log density of run b's values :math:v_b alone, with the change-of-variables term of each site's bijector at :math:v_b: it equals the density log_prob gives with a one-row input and run b's values, whatever the other runs hold. A shared value thus enters every run's density in full.

The draws rsample returns for the B runs each follow :math:q_\phi, but need not be independent of one another: a guide with one joint draw (AutoMultivariateNormalGuide, a flow, AutoStructured, AutoLaplaceApproximation) gives every run the same draw. log_prob scores any values, its own draws or not.

PARAMETER DESCRIPTION
x

Program input; its leading axis has one row per run.

TYPE: Tensor

sites

Constrained values of the sites the guide covers, each one per run or one the runs share.

TYPE: dict[str, Tensor]

RETURNS DESCRIPTION
Tensor

Shape (B,).

Source code in src/quivers/inference/guides/base.py
@abstractmethod
def log_prob(
    self,
    x: torch.Tensor,
    sites: dict[str, torch.Tensor],
) -> torch.Tensor:
    """Log density of ``sites`` under :math:`q_\\phi(z \\mid x)`, run by run.

    An input ``x`` of ``B`` rows is ``B`` independent runs of the
    program, and the guide's law :math:`q_\\phi` is a law over the
    latents of one run. The value of each site in ``sites`` either
    has a leading run axis, shape ``(B, *constrained_shape)``, with
    run ``b``'s value at index ``b``, or has shape
    `LatentSite.constrained_shape` and is one value every run
    shares; `LatentSite.align_runs` states the rule, and any other
    shape is refused. Entry ``b`` of the result is
    :math:`\\log q_\\phi(v_b)`, the log density of run ``b``'s
    values :math:`v_b` alone, with the change-of-variables term of
    each site's bijector at :math:`v_b`: it equals the density
    ``log_prob`` gives with a one-row input and run ``b``'s values,
    whatever the other runs hold. A shared value thus enters every
    run's density in full.

    The draws `rsample` returns for the ``B`` runs each follow
    :math:`q_\\phi`, but need not be independent of one another: a
    guide with one joint draw (`AutoMultivariateNormalGuide`, a
    flow, `AutoStructured`, `AutoLaplaceApproximation`) gives every
    run the same draw. `log_prob` scores any values, its own draws
    or not.

    Parameters
    ----------
    x : torch.Tensor
        Program input; its leading axis has one row per run.
    sites : dict[str, torch.Tensor]
        Constrained values of the sites the guide covers, each one
        per run or one the runs share.

    Returns
    -------
    torch.Tensor
        Shape ``(B,)``.
    """
    ...

GuideDraw didactic-model

GuideDraw(*, sites: dict[str, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), log_density: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), log_weight: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

One weighted draw from a guide, scored by the guide.

The site tensors, density, and weight compare by identity: two draws are equal exactly when they hold the same tensor objects.

PARAMETER DESCRIPTION
sites

Per-site constrained values, shaped as Guide.rsample's output.

TYPE: dict[str, Tensor] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

log_density

The guide log-density of this draw, shape (batch,), with gradients to the variational parameters through the draw and directly. For most guides it is Guide.log_prob at sites; for AutoDAIS it is the extended-space density of the trajectory that produced the draw.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

log_weight

Scalar log-weight :math:\log \omega of the stratum the draw represents; zero for a guide that is not stratified.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

AutoDeltaGuide

AutoDeltaGuide(model: MonadicProgram, observed_names: set[str], init_value: float = 0.0, *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None)

Bases: Guide

Dirac-delta MAP guide with per-site constrained bijector.

PARAMETER DESCRIPTION
model

Generative model.

TYPE: MonadicProgram

observed_names

Variable names treated as observations.

TYPE: set[str]

x

Keyword-only. A program input at which to build the latent registry from a run, required for a program that scans or calls a program that draws, whose latent sites depend on its input.

TYPE: Tensor | None DEFAULT: None

observations

Keyword-only. The observed values and host data of that run.

TYPE: dict[str, Tensor] | None DEFAULT: None

init_value

Initial unconstrained-space coordinate for every latent. Default 0.0; for the standard bijectors this maps to a sensible interior point of each support (the median of a HalfNormal, the centre of the unit interval, the uniform Dirichlet, etc.). Small Gaussian noise is added so two coordinate values don't collide.

TYPE: float DEFAULT: 0.0

Notes

The guide's density is constant, so it scores a latent in a subsampled plate as it scores every other latent.

Source code in src/quivers/inference/guides/delta.py
def __init__(
    self,
    model: MonadicProgram,
    observed_names: set[str],
    init_value: float = 0.0,
    *,
    x: torch.Tensor | None = None,
    observations: dict[str, torch.Tensor] | None = None,
) -> None:
    super().__init__()
    self._registry = self.build_registry(
        model, observed_names, x=x, observations=observations
    )

    for site in self._registry.sites.values():
        self.register_parameter(
            f"unconstrained_{site.name}",
            nn.Parameter(
                torch.full(site.unconstrained_shape, init_value)
                + torch.randn(site.unconstrained_shape) * 0.01
            ),
        )

rsample

rsample(x: Tensor) -> dict[str, Tensor]

Return the learned point estimates in the prior's support.

Source code in src/quivers/inference/guides/delta.py
def rsample(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
    """Return the learned point estimates in the prior's
    support."""
    batch = x.shape[0]
    return {
        site.name: self._push_through_bijector(site, batch)
        for site in self._registry.sites.values()
    }

log_prob

log_prob(x: Tensor, sites: dict[str, Tensor]) -> Tensor

Delta log-density of each run: zero (the delta term and its Jacobian cancel in the ELBO under the standard score-function trick).

The values are still checked against the run-wise contract of Guide.log_prob.

PARAMETER DESCRIPTION
x

Program input; its leading axis has one row per run.

TYPE: Tensor

sites

Constrained values of every latent site, each one per run or one the runs share.

TYPE: dict[str, Tensor]

RETURNS DESCRIPTION
Tensor

Zeros of shape (B,).

RAISES DESCRIPTION
KeyError

If a latent site is missing from sites.

ValueError

If a value is neither one per run nor one the runs share.

Source code in src/quivers/inference/guides/delta.py
def log_prob(
    self,
    x: torch.Tensor,
    sites: dict[str, torch.Tensor],
) -> torch.Tensor:
    """Delta log-density of each run: zero (the delta term and its
    Jacobian cancel in the ELBO under the standard score-function
    trick).

    The values are still checked against the run-wise contract of
    `Guide.log_prob`.

    Parameters
    ----------
    x : torch.Tensor
        Program input; its leading axis has one row per run.
    sites : dict[str, torch.Tensor]
        Constrained values of every latent site, each one per run or
        one the runs share.

    Returns
    -------
    torch.Tensor
        Zeros of shape ``(B,)``.

    Raises
    ------
    KeyError
        If a latent site is missing from ``sites``.
    ValueError
        If a value is neither one per run nor one the runs share.
    """
    runs = int(x.shape[0])
    for site in self._registry.sites.values():
        if site.name not in sites:
            raise KeyError(f"AutoDeltaGuide.log_prob: missing site {site.name!r}")
        site.align_runs(sites[site.name], runs)
    return torch.zeros(runs, device=x.device)

AutoIAFGuide

AutoIAFGuide(model: MonadicProgram, observed_names: set[str], num_flows: int = 4, hidden_dim: int | None = None, num_hidden_layers: int = 2, *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None)

Bases: AutoNormalizingFlow

Inverse-autoregressive-flow guide.

Default normalizing-flow guide for variational inference (Kingma-Salimans-Jozefowicz et al. 2016). Stack of InverseAutoregressiveTransform layers, each separated by a reverse permutation so successive layers have different autoregressive orderings.

Sampling is parallel (one MLP forward per layer); density evaluation is sequential (one coordinate at a time per layer), so this guide should be used with objectives that sample more than they score the same flow (ELBO, IWAE).

PARAMETER DESCRIPTION
model

Generative model.

TYPE: MonadicProgram

observed_names

Variable names treated as observations.

TYPE: set[str]

x

Keyword-only. A program input at which to build the latent registry from a run, required for a program that scans or calls a program that draws, whose latent sites depend on its input.

TYPE: Tensor | None DEFAULT: None

observations

Keyword-only. The observed values and host data of that run.

TYPE: dict[str, Tensor] | None DEFAULT: None

num_flows

Number of IAF blocks in the stack. Default 4.

TYPE: int DEFAULT: 4

hidden_dim

Hidden width of every MADE inside the stack. Default 2 * D where D is the latent dimension.

TYPE: int DEFAULT: None

num_hidden_layers

Number of hidden layers in each MADE. Default 2.

TYPE: int DEFAULT: 2

Source code in src/quivers/inference/guides/flow.py
def __init__(
    self,
    model: MonadicProgram,
    observed_names: set[str],
    num_flows: int = 4,
    hidden_dim: int | None = None,
    num_hidden_layers: int = 2,
    *,
    x: torch.Tensor | None = None,
    observations: dict[str, torch.Tensor] | None = None,
) -> None:
    if num_flows < 1:
        raise ValueError(f"AutoIAFGuide: num_flows must be >= 1, got {num_flows}")
    registry = Guide.build_registry(
        model, observed_names, x=x, observations=observations
    )
    D_total = registry.total_unconstrained_dim
    if hidden_dim is None:
        hidden_dim = max(8, 2 * D_total)
    if D_total < 2:
        raise ValueError(
            f"AutoIAFGuide: model must have >= 2 unconstrained "
            f"latent dimensions for an IAF (got {D_total}); use "
            f"AutoNormalGuide for 1-D models"
        )
    layers: list[TransformModule] = []
    for i in range(num_flows):
        made = MADE(
            dim=D_total,
            n_per_dim=2,
            hidden=hidden_dim,
            n_hidden_layers=num_hidden_layers,
        )
        layers.append(InverseAutoregressiveTransform(made))
        if i < num_flows - 1:
            layers.append(_ReversePermutation(D_total))
    super().__init__(model, observed_names, layers, x=x, observations=observations)

AutoNeuralSplineGuide

AutoNeuralSplineGuide(model: MonadicProgram, observed_names: set[str], num_flows: int = 4, num_bins: int = 8, tail_bound: float = 3.0, hidden_dim: int | None = None, num_hidden_layers: int = 2, *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None)

Bases: AutoNormalizingFlow

Neural-spline-flow guide (Durkan-Bekasov-Murray-Papamakarios 2019).

Stack of monotone rational-quadratic spline coupling layers (NeuralSplineCouplingTransform) with alternating half-masks. Sharper than IAF for posteriors with bounded support or sharp modes; comparable runtime.

PARAMETER DESCRIPTION
model

Generative model.

TYPE: MonadicProgram

observed_names

Variable names treated as observations.

TYPE: set[str]

x

Keyword-only. A program input at which to build the latent registry from a run, required for a program that scans or calls a program that draws, whose latent sites depend on its input.

TYPE: Tensor | None DEFAULT: None

observations

Keyword-only. The observed values and host data of that run.

TYPE: dict[str, Tensor] | None DEFAULT: None

num_flows

Number of coupling layers. Default 4.

TYPE: int DEFAULT: 4

num_bins

Number of spline bins per coordinate. Default 8.

TYPE: int DEFAULT: 8

tail_bound

Inputs outside [-tail_bound, tail_bound] pass through as identity. Default 3.0.

TYPE: float DEFAULT: 3.0

hidden_dim

Hidden width of the coupling MLPs. Default max(64, 2*D).

TYPE: int DEFAULT: None

num_hidden_layers

Hidden layers in each coupling MLP. Default 2.

TYPE: int DEFAULT: 2

Source code in src/quivers/inference/guides/flow.py
def __init__(
    self,
    model: MonadicProgram,
    observed_names: set[str],
    num_flows: int = 4,
    num_bins: int = 8,
    tail_bound: float = 3.0,
    hidden_dim: int | None = None,
    num_hidden_layers: int = 2,
    *,
    x: torch.Tensor | None = None,
    observations: dict[str, torch.Tensor] | None = None,
) -> None:
    if num_flows < 1:
        raise ValueError(
            f"AutoNeuralSplineGuide: num_flows must be >= 1, got {num_flows}"
        )
    registry = Guide.build_registry(
        model, observed_names, x=x, observations=observations
    )
    D_total = registry.total_unconstrained_dim
    if D_total < 2:
        raise ValueError(
            f"AutoNeuralSplineGuide: model must have >= 2 "
            f"unconstrained latent dimensions for a spline "
            f"coupling flow (got {D_total})"
        )
    if hidden_dim is None:
        hidden_dim = max(64, 2 * D_total)
    layers: list[TransformModule] = []
    for i in range(num_flows):
        mask = alternating_mask(D_total, even=(i % 2 == 0))
        num_unmasked = int(mask.sum().item())
        num_masked = D_total - num_unmasked
        # Net produces (3 * num_bins - 1) parameters per masked coord.
        out_dim = num_masked * (3 * num_bins - 1)
        net = make_coupling_mlp(
            n_in=num_unmasked,
            n_out=out_dim,
            hidden=hidden_dim,
            n_hidden_layers=num_hidden_layers,
        )
        layers.append(
            NeuralSplineCouplingTransform(
                dim=D_total,
                net=net,
                mask=mask,
                num_bins=num_bins,
                tail_bound=tail_bound,
            )
        )
    super().__init__(model, observed_names, layers, x=x, observations=observations)

AutoNormalizingFlow

AutoNormalizingFlow(model: MonadicProgram, observed_names: set[str], transforms: list[TransformModule], *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None)

Bases: Guide

Normalising-flow variational guide over the flat latent vector.

PARAMETER DESCRIPTION
model

Generative model to build a guide for.

TYPE: MonadicProgram

observed_names

Variable names treated as observations.

TYPE: set[str]

x

Keyword-only. A program input at which to build the latent registry from a run, required for a program that scans or calls a program that draws, whose latent sites depend on its input.

TYPE: Tensor | None DEFAULT: None

observations

Keyword-only. The observed values and host data of that run.

TYPE: dict[str, Tensor] | None DEFAULT: None

transforms

Flow stack applied to the standard-Normal base. Each TransformModule must accept a (..., D)-shaped tensor where D is the registry's total unconstrained dimension.

TYPE: list[TransformModule]

Source code in src/quivers/inference/guides/flow.py
def __init__(
    self,
    model: MonadicProgram,
    observed_names: set[str],
    transforms: list[TransformModule],
    *,
    x: torch.Tensor | None = None,
    observations: dict[str, torch.Tensor] | None = None,
) -> None:
    super().__init__()
    self._registry = self.build_registry(
        model, observed_names, x=x, observations=observations
    )
    D_total = self._registry.total_unconstrained_dim
    if D_total == 0:
        raise ValueError(
            f"{type(self).__name__}: registry has zero total "
            f"unconstrained dimension; model has no continuous "
            f"latents to guide"
        )
    if not transforms:
        raise ValueError(
            f"{type(self).__name__}: transforms list must be non-empty"
        )
    self._D = D_total
    self.flow = nn.ModuleList(transforms)
    self._layers: list[TransformModule] = list(transforms)
    self.register_buffer("base_loc", torch.zeros(D_total))
    self.register_buffer("base_scale", torch.ones(D_total))

push_forward

push_forward(z0: Tensor) -> tuple[Tensor, Tensor]

Push base points through the flow.

PARAMETER DESCRIPTION
z0

Points of the base space, shape (..., D); each row is mapped alone.

TYPE: Tensor

RETURNS DESCRIPTION
tuple[Tensor, Tensor]

The images :math:z_K = T_K \circ \dots \circ T_1(z_0) and :math:\sum_k \log|\det J_{T_k}| along the way, shape z0.shape[:-1].

Source code in src/quivers/inference/guides/flow.py
def push_forward(self, z0: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
    """Push base points through the flow.

    Parameters
    ----------
    z0 : torch.Tensor
        Points of the base space, shape ``(..., D)``; each row is
        mapped alone.

    Returns
    -------
    tuple[torch.Tensor, torch.Tensor]
        The images :math:`z_K = T_K \\circ \\dots \\circ T_1(z_0)`
        and :math:`\\sum_k \\log|\\det J_{T_k}|` along the way,
        shape ``z0.shape[:-1]``.
    """
    log_det_total = torch.zeros(z0.shape[:-1], device=z0.device, dtype=z0.dtype)
    z = z0
    for layer in self._layers:
        z_next = _tensor(layer(z), layer)
        log_det_total = log_det_total + layer.log_abs_det_jacobian(z, z_next)
        z = z_next
    return z, log_det_total

pull_back

pull_back(z_K: Tensor) -> tuple[Tensor, Tensor]

Pull points of the flow's codomain back to the base space.

PARAMETER DESCRIPTION
z_K

Points of the codomain, shape (..., D); each row is mapped alone.

TYPE: Tensor

RETURNS DESCRIPTION
tuple[Tensor, Tensor]

The base points :math:z_0 and the forward :math:\sum_k \log|\det J_{T_k}| at them, so that :math:\log q(z_K) = \log p_0(z_0) - \sum_k \log|\det J_{T_k}|.

Source code in src/quivers/inference/guides/flow.py
def pull_back(self, z_K: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
    """Pull points of the flow's codomain back to the base space.

    Parameters
    ----------
    z_K : torch.Tensor
        Points of the codomain, shape ``(..., D)``; each row is
        mapped alone.

    Returns
    -------
    tuple[torch.Tensor, torch.Tensor]
        The base points :math:`z_0` and the forward
        :math:`\\sum_k \\log|\\det J_{T_k}|` at them, so that
        :math:`\\log q(z_K) = \\log p_0(z_0) - \\sum_k
        \\log|\\det J_{T_k}|`.
    """
    log_det_total = torch.zeros(z_K.shape[:-1], device=z_K.device, dtype=z_K.dtype)
    z = z_K
    for layer in reversed(self._layers):
        z_prev = _tensor(layer.inv(z), layer)
        log_det_total = log_det_total + layer.log_abs_det_jacobian(z_prev, z)
        z = z_prev
    return z, log_det_total

update_statistics

update_statistics(num_draws: int) -> None

Refresh every layer's data-dependent state from base draws.

Draws num_draws base points, and walks the stack: each layer folds the batch of its inputs into its state (TransformModule.update_statistics) and then maps the batch on, so a later layer sees the inputs the updated earlier layers give it. Objectives never call this; call it between steps.

PARAMETER DESCRIPTION
num_draws

Number of base draws, at least two.

TYPE: int

RAISES DESCRIPTION
ValueError

If num_draws is less than two.

Source code in src/quivers/inference/guides/flow.py
def update_statistics(self, num_draws: int) -> None:
    """Refresh every layer's data-dependent state from base draws.

    Draws ``num_draws`` base points, and walks the stack: each layer
    folds the batch of its inputs into its state
    (`TransformModule.update_statistics`) and then maps the batch
    on, so a later layer sees the inputs the updated earlier layers
    give it. Objectives never call this; call it between steps.

    Parameters
    ----------
    num_draws : int
        Number of base draws, at least two.

    Raises
    ------
    ValueError
        If ``num_draws`` is less than two.
    """
    if num_draws < 2:
        raise ValueError(
            f"{type(self).__name__}.update_statistics: num_draws must be >= 2, "
            f"got {num_draws}"
        )
    with torch.no_grad():
        z = self._base_dist().sample((num_draws,))
        for layer in self._layers:
            layer.update_statistics(z)
            z = _tensor(layer(z), layer)

rsample

rsample(x: Tensor) -> dict[str, Tensor]

One flow draw, unflattened and bijected to constrained space.

Source code in src/quivers/inference/guides/flow.py
def rsample(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
    """One flow draw, unflattened and bijected to constrained space."""
    batch = x.shape[0]
    z0 = self._base_dist().rsample()
    z_K, _ = self.push_forward(z0)
    per_site = self._registry.unflatten_unconstrained(z_K)
    result: dict[str, torch.Tensor] = {}
    for site in self._registry.sites.values():
        z_site = per_site[site.name]
        if not site.is_plate:
            z_site = z_site.unsqueeze(0).expand(batch, *site.unconstrained_shape)
        v, _ = site.constrain(z_site)
        result[site.name] = v
    return result

log_prob

log_prob(x: Tensor, sites: dict[str, Tensor]) -> Tensor

Log-density of each run's constrained values.

For run b the flat unconstrained point :math:z_{K,b} of its values, read by LatentRegistry.unconstrain_runs, is pulled back through the flow, and :math:\log q(v_b) = \log p_0(z_{0,b}) - \sum_k \log|\det J_{T_k}| + \sum_i \log|\det J_{T_i^{-1}}(v_{b,i})|, the last sum over the per-site bijectors. Every transform in quivers.inference.transforms maps each row of the (B, D) matrix of points alone.

PARAMETER DESCRIPTION
x

Program input; its leading axis has one row per run.

TYPE: Tensor

sites

Constrained values of every latent site, each one per run or one the runs share (Guide.log_prob).

TYPE: dict[str, Tensor]

RETURNS DESCRIPTION
Tensor

Shape (B,), one log density per run.

RAISES DESCRIPTION
KeyError

If a latent site is missing from sites.

ValueError

If a value is neither one per run nor one the runs share.

Source code in src/quivers/inference/guides/flow.py
def log_prob(
    self,
    x: torch.Tensor,
    sites: dict[str, torch.Tensor],
) -> torch.Tensor:
    """Log-density of each run's constrained values.

    For run ``b`` the flat unconstrained point :math:`z_{K,b}` of its
    values, read by `LatentRegistry.unconstrain_runs`, is pulled back
    through the flow, and
    :math:`\\log q(v_b) = \\log p_0(z_{0,b}) - \\sum_k \\log|\\det J_{T_k}|
    + \\sum_i \\log|\\det J_{T_i^{-1}}(v_{b,i})|`, the last sum over
    the per-site bijectors. Every transform in
    [`quivers.inference.transforms`][quivers.inference.transforms]
    maps each row of the ``(B, D)`` matrix of points alone.

    Parameters
    ----------
    x : torch.Tensor
        Program input; its leading axis has one row per run.
    sites : dict[str, torch.Tensor]
        Constrained values of every latent site, each one per run or
        one the runs share (`Guide.log_prob`).

    Returns
    -------
    torch.Tensor
        Shape ``(B,)``, one log density per run.

    Raises
    ------
    KeyError
        If a latent site is missing from ``sites``.
    ValueError
        If a value is neither one per run nor one the runs share.
    """
    coordinates = self._registry.unconstrain_runs(sites, int(x.shape[0]))
    z_K = self._registry.flatten_unconstrained(coordinates.unconstrained)
    z_0, flow_log_det = self.pull_back(z_K)
    log_q_z = self._base_dist().log_prob(z_0) - flow_log_det
    return log_q_z + coordinates.total_log_abs_det()

AutoLaplaceApproximation

AutoLaplaceApproximation(model: MonadicProgram, observed_names: set[str], init_value: float = 0.0, *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None)

Bases: Guide

Laplace-approximation guide.

PARAMETER DESCRIPTION
model

Generative model.

TYPE: MonadicProgram

observed_names

Variable names treated as observations.

TYPE: set[str]

x

Keyword-only. A program input at which to build the latent registry from a run, required for a program that scans or calls a program that draws, whose latent sites depend on its input.

TYPE: Tensor | None DEFAULT: None

observations

Keyword-only. The observed values and host data of that run.

TYPE: dict[str, Tensor] | None DEFAULT: None

init_value

Initial unconstrained-space MAP estimate. Default 0.0.

TYPE: float DEFAULT: 0.0

Source code in src/quivers/inference/guides/laplace.py
def __init__(
    self,
    model: MonadicProgram,
    observed_names: set[str],
    init_value: float = 0.0,
    *,
    x: torch.Tensor | None = None,
    observations: dict[str, torch.Tensor] | None = None,
) -> None:
    super().__init__()
    self._registry = self.build_registry(
        model, observed_names, x=x, observations=observations
    )
    D_total = self._registry.total_unconstrained_dim
    if D_total == 0:
        raise ValueError(
            f"{type(self).__name__}: registry has zero total "
            f"unconstrained dimension; model has no continuous "
            f"latents to guide"
        )
    self._D = D_total
    # MAP estimate in flat unconstrained space.
    init = torch.full((D_total,), float(init_value))
    init = init + 0.01 * torch.randn(D_total)
    self.map_z = nn.Parameter(init)
    # Hessian-phase parameters; initialized to identity scale_tril
    # but only used after fit_hessian() is called.
    self.register_buffer("_hessian_fitted", torch.zeros((), dtype=torch.bool))
    self.register_buffer(
        "_scale_tril",
        torch.eye(D_total) * 1e-3,
        persistent=True,
    )

hessian_fitted property

hessian_fitted: bool

Whether fit_hessian has been called.

fit_hessian

fit_hessian(model: MonadicProgram, x: Tensor, observations: dict[str, Tensor], *, jitter: float = 0.0001) -> None

Compute and cache the Hessian-derived Cholesky factor.

Solves the eigenproblem of the negative-log-joint Hessian at the current MAP, projects negative eigenvalues to jitter (so the resulting Gaussian is always positive-definite), and stores the matching lower-triangular Cholesky factor of the inverse Hessian as the posterior scale_tril.

Call this after MAP optimization has converged. Subsequent rsample / log_prob calls sample from :math:\mathcal{N}(z^\star, H^{-1}).

PARAMETER DESCRIPTION
model

The model whose joint the Hessian is taken of.

TYPE: MonadicProgram

x

Program input: one row, since the approximation is of one run's posterior.

TYPE: Tensor

observations

Observed-site values and host data.

TYPE: dict[str, Tensor]

jitter

The floor every eigenvalue of the Hessian is projected to.

TYPE: float DEFAULT: 0.0001

RAISES DESCRIPTION
ValueError

If x has more than one row.

Source code in src/quivers/inference/guides/laplace.py
def fit_hessian(
    self,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.Tensor],
    *,
    jitter: float = 1e-4,
) -> None:
    """Compute and cache the Hessian-derived Cholesky factor.

    Solves the eigenproblem of the negative-log-joint Hessian at
    the current MAP, projects negative eigenvalues to ``jitter``
    (so the resulting Gaussian is always positive-definite), and
    stores the matching lower-triangular Cholesky factor of the
    inverse Hessian as the posterior scale_tril.

    Call this after MAP optimization has converged. Subsequent
    `rsample` / `log_prob` calls sample from
    :math:`\\mathcal{N}(z^\\star, H^{-1})`.

    Parameters
    ----------
    model : MonadicProgram
        The model whose joint the Hessian is taken of.
    x : torch.Tensor
        Program input: one row, since the approximation is of one
        run's posterior.
    observations : dict[str, torch.Tensor]
        Observed-site values and host data.
    jitter : float
        The floor every eigenvalue of the Hessian is projected to.

    Raises
    ------
    ValueError
        If ``x`` has more than one row.
    """
    _require_one_run(x, "AutoLaplaceApproximation.fit_hessian")

    def neg_log_joint(z_flat: torch.Tensor) -> torch.Tensor:
        per_site_unconstrained = self._registry.unflatten_unconstrained(z_flat)
        constrained: dict[str, torch.Tensor] = {}
        log_det_sum = torch.zeros((), device=z_flat.device)
        for site in self._registry.sites.values():
            z_site = per_site_unconstrained[site.name]
            if not site.is_plate:
                z_site = z_site.unsqueeze(0)
            v, log_det = site.constrain(z_site)
            log_det_sum = log_det_sum + log_det.sum()
            constrained[site.name] = v
        log_p = model.log_joint(x, {**constrained, **observations})
        return -(log_p.sum() + log_det_sum)

    H = torch.autograd.functional.hessian(neg_log_joint, self.map_z.detach())
    H = 0.5 * (H + H.t())
    eigvals, eigvecs = torch.linalg.eigh(H)
    eigvals_clamped = eigvals.clamp(min=jitter)
    # Σ = (V Λ V^T)^{-1} = V Λ^{-1} V^T; scale_tril is its Cholesky.
    inv_eigvals = 1.0 / eigvals_clamped
    sigma = (eigvecs * inv_eigvals.unsqueeze(0)) @ eigvecs.t()
    sigma = 0.5 * (sigma + sigma.t())
    sigma = sigma + jitter * torch.eye(self._D, device=sigma.device)
    L = torch.linalg.cholesky(sigma)
    self.get_buffer("_scale_tril").copy_(L)
    self.get_buffer("_hessian_fitted").fill_(True)

rsample

rsample(x: Tensor) -> dict[str, Tensor]

Sample from the Laplace posterior, unflatten, and biject.

Source code in src/quivers/inference/guides/laplace.py
def rsample(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
    """Sample from the Laplace posterior, unflatten, and biject."""
    batch = x.shape[0]
    z_flat = self._sample_unconstrained()
    per_site = self._registry.unflatten_unconstrained(z_flat)

    result: dict[str, torch.Tensor] = {}
    for site in self._registry.sites.values():
        z_site = per_site[site.name]
        if not site.is_plate:
            z_site = z_site.unsqueeze(0).expand(batch, *site.unconstrained_shape)
        v, _ = site.constrain(z_site)
        result[site.name] = v
    return result

log_prob

log_prob(x: Tensor, sites: dict[str, Tensor]) -> Tensor

Log-density of each run's constrained values.

Returns zero for every run before fit_hessian (MAP-phase delta convention); after fit_hessian returns, for run b, the Gaussian log-density of run b's flat unconstrained point plus the per-site bijector Jacobian correction at its values, read by LatentRegistry.unconstrain_runs.

PARAMETER DESCRIPTION
x

Program input; its leading axis has one row per run.

TYPE: Tensor

sites

Constrained values of every latent site, each one per run or one the runs share (Guide.log_prob).

TYPE: dict[str, Tensor]

RETURNS DESCRIPTION
Tensor

Shape (B,), one log density per run.

RAISES DESCRIPTION
KeyError

If a latent site is missing from sites.

ValueError

If a value is neither one per run nor one the runs share.

Source code in src/quivers/inference/guides/laplace.py
def log_prob(
    self,
    x: torch.Tensor,
    sites: dict[str, torch.Tensor],
) -> torch.Tensor:
    """Log-density of each run's constrained values.

    Returns zero for every run before `fit_hessian` (MAP-phase delta
    convention); after `fit_hessian` returns, for run ``b``, the
    Gaussian log-density of run ``b``'s flat unconstrained point plus
    the per-site bijector Jacobian correction at its values, read by
    `LatentRegistry.unconstrain_runs`.

    Parameters
    ----------
    x : torch.Tensor
        Program input; its leading axis has one row per run.
    sites : dict[str, torch.Tensor]
        Constrained values of every latent site, each one per run or
        one the runs share (`Guide.log_prob`).

    Returns
    -------
    torch.Tensor
        Shape ``(B,)``, one log density per run.

    Raises
    ------
    KeyError
        If a latent site is missing from ``sites``.
    ValueError
        If a value is neither one per run nor one the runs share.
    """
    runs = int(x.shape[0])
    coordinates = self._registry.unconstrain_runs(sites, runs)
    if not bool(self._hessian_fitted):
        return torch.zeros(runs, device=x.device)
    z_flat = self._registry.flatten_unconstrained(coordinates.unconstrained)
    gauss = D.MultivariateNormal(
        self.map_z, scale_tril=self.get_buffer("_scale_tril")
    )
    return gauss.log_prob(z_flat) + coordinates.total_log_abs_det()

AutoMixtureGuide

AutoMixtureGuide(components: list[Guide])

Bases: Guide

Finite mixture variational guide.

PARAMETER DESCRIPTION
components

Component guides. All components must share the same LatentRegistry (i.e. be built against the same model + observed-name set).

TYPE: list[Guide]

RAISES DESCRIPTION
ValueError

If fewer than two components are given, or if the components cover different latent names.

Source code in src/quivers/inference/guides/mixture.py
def __init__(self, components: list[Guide]) -> None:
    super().__init__()
    if len(components) < 2:
        raise ValueError(
            f"AutoMixtureGuide: need at least 2 components, got {len(components)}"
        )
    reference = components[0]
    ref_names = tuple(reference.registry.names)
    for i, comp in enumerate(components[1:], 1):
        comp_names = tuple(comp.registry.names)
        if comp_names != ref_names:
            raise ValueError(
                f"AutoMixtureGuide: component {i} has different "
                f"latent names {comp_names!r} than component 0 "
                f"{ref_names!r}"
            )
    self._registry = reference.registry
    self._component_guides: list[Guide] = list(components)
    self.components = nn.ModuleList(components)
    self.mixture_logits = nn.Parameter(torch.zeros(len(components)))

num_components property

num_components: int

Number of mixture components.

RETURNS DESCRIPTION
int

The component count :math:K.

latent_names property

latent_names: list[str]

Names of the latent sites the mixture covers.

RETURNS DESCRIPTION
list[str]

The registry's site names, in order.

mixture_weights

mixture_weights() -> Tensor

Mixture weights :math:\pi = \mathrm{softmax}(\text{logits}).

RETURNS DESCRIPTION
Tensor

Shape (K,), non-negative and summing to one.

Source code in src/quivers/inference/guides/mixture.py
def mixture_weights(self) -> torch.Tensor:
    """Mixture weights :math:`\\pi = \\mathrm{softmax}(\\text{logits})`.

    Returns
    -------
    torch.Tensor
        Shape ``(K,)``, non-negative and summing to one.
    """
    return F.softmax(self.mixture_logits, dim=-1)

observe

observe(observations: Mapping[str, Tensor]) -> None

Forward the step's data to every component.

PARAMETER DESCRIPTION
observations

Observed values and host data.

TYPE: Mapping[str, Tensor]

Source code in src/quivers/inference/guides/mixture.py
def observe(self, observations: Mapping[str, torch.Tensor]) -> None:
    """Forward the step's data to every component.

    Parameters
    ----------
    observations : Mapping[str, torch.Tensor]
        Observed values and host data.
    """
    for component in self._component_guides:
        component.observe(observations)

rsample

rsample(x: Tensor) -> dict[str, Tensor]

Draw from the mixture density that log_prob scores.

Samples a component index :math:k \sim \mathrm{Categorical}(\pi) and returns component k's reparameterized draw. One index is drawn per call and shared across the batch rows, so a plate latent and the per-row latents of every row come from the same component, matching the per-row joint density log_prob evaluates.

Gradients reach the chosen component's parameters but not the mixture logits, since the component choice is discrete. The variational objectives train the logits through rsample_strata instead.

PARAMETER DESCRIPTION
x

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

TYPE: Tensor

RETURNS DESCRIPTION
dict[str, Tensor]

Per-site constrained draws from the mixture.

Source code in src/quivers/inference/guides/mixture.py
def rsample(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
    """Draw from the mixture density that `log_prob` scores.

    Samples a component index :math:`k \\sim
    \\mathrm{Categorical}(\\pi)` and returns component ``k``'s
    reparameterized draw. One index is drawn per call and shared
    across the batch rows, so a plate latent and the per-row
    latents of every row come from the same component, matching
    the per-row joint density `log_prob` evaluates.

    Gradients reach the chosen component's parameters but not
    the mixture logits, since the component choice is discrete.
    The variational objectives train the logits through
    `rsample_strata` instead.

    Parameters
    ----------
    x : torch.Tensor
        Program input. Shape ``(batch, ...)``.

    Returns
    -------
    dict[str, torch.Tensor]
        Per-site constrained draws from the mixture.
    """
    with torch.no_grad():
        index = int(
            torch.distributions.Categorical(logits=self.mixture_logits)
            .sample()
            .item()
        )
    return self._component_guides[index].rsample(x)

rsample_strata

rsample_strata(x: Tensor) -> tuple[GuideDraw, ...]

Enumerate the components as strata.

Each component contributes its own strata (one for an ordinary component, several for a nested mixture), with the component's log mixture weight added to their log-weights and each draw scored by the mixture density. The resulting weights sum to one and the strata partition the mixture density, so :math:\sum_s \omega_s f(z_s) estimates :math:\mathbb{E}_q[f] without bias, with gradients to the mixture logits through :math:\omega_s and the density.

PARAMETER DESCRIPTION
x

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

TYPE: Tensor

RETURNS DESCRIPTION
tuple[GuideDraw, ...]

One weighted draw per stratum, S in total over the components.

Source code in src/quivers/inference/guides/mixture.py
def rsample_strata(self, x: torch.Tensor) -> tuple[GuideDraw, ...]:
    """Enumerate the components as strata.

    Each component contributes its own strata (one for an
    ordinary component, several for a nested mixture), with the
    component's log mixture weight added to their log-weights and
    each draw scored by the mixture density. The resulting weights
    sum to one and the strata partition the mixture density, so
    :math:`\\sum_s \\omega_s f(z_s)` estimates
    :math:`\\mathbb{E}_q[f]` without bias, with gradients to the
    mixture logits through :math:`\\omega_s` and the density.

    Parameters
    ----------
    x : torch.Tensor
        Program input. Shape ``(batch, ...)``.

    Returns
    -------
    tuple[GuideDraw, ...]
        One weighted draw per stratum, ``S`` in total over the
        components.
    """
    log_pi = F.log_softmax(self.mixture_logits, dim=-1)
    draws: list[GuideDraw] = []
    for k, component in enumerate(self._component_guides):
        for draw in component.rsample_strata(x):
            draws.append(
                GuideDraw(
                    sites=draw.sites,
                    log_density=self.log_prob(x, draw.sites),
                    log_weight=log_pi[k] + draw.log_weight.to(dtype=log_pi.dtype),
                )
            )
    return tuple(draws)

log_prob

log_prob(x: Tensor, sites: dict[str, Tensor]) -> Tensor

Mixture log-density via logsumexp over components.

PARAMETER DESCRIPTION
x

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

TYPE: Tensor

sites

Per-site constrained values to score.

TYPE: dict[str, Tensor]

RETURNS DESCRIPTION
Tensor

:math:\log \sum_k \pi_k q_k(z), shape (batch,).

Source code in src/quivers/inference/guides/mixture.py
def log_prob(
    self,
    x: torch.Tensor,
    sites: dict[str, torch.Tensor],
) -> torch.Tensor:
    """Mixture log-density via logsumexp over components.

    Parameters
    ----------
    x : torch.Tensor
        Program input. Shape ``(batch, ...)``.
    sites : dict[str, torch.Tensor]
        Per-site constrained values to score.

    Returns
    -------
    torch.Tensor
        :math:`\\log \\sum_k \\pi_k q_k(z)`, shape ``(batch,)``.
    """
    log_pi = F.log_softmax(self.mixture_logits, dim=-1)
    component_log_probs = torch.stack(
        [comp.log_prob(x, sites) for comp in self._component_guides], dim=0
    )
    return torch.logsumexp(log_pi.unsqueeze(-1) + component_log_probs, dim=0)

AutoLowRankMultivariateNormalGuide

AutoLowRankMultivariateNormalGuide(model: MonadicProgram, observed_names: set[str], rank: int = 5, init_scale: float = 0.1, *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None)

Bases: _MVNCommon

Low-rank-plus-diagonal multivariate-Normal guide.

Covariance :math:\Sigma = W W^\top + \mathrm{diag}(\sigma^2) with W of shape :math:(D, r) and :math:\sigma \in \mathbb{R}^{D}_{>0}. Memory :math:O(Dr); sampling and log-density via Woodbury / matrix-determinant lemma in torch.distributions.LowRankMultivariateNormal.

Captures the dominant r posterior correlation directions while remaining tractable for D in the hundreds-to- thousands range, where full-rank is infeasible.

PARAMETER DESCRIPTION
model

Generative model to build a guide for.

TYPE: MonadicProgram

observed_names

Variable names treated as observations.

TYPE: set[str]

x

Keyword-only. A program input at which to build the latent registry from a run, required for a program that scans or calls a program that draws, whose latent sites depend on its input.

TYPE: Tensor | None DEFAULT: None

observations

Keyword-only. The observed values and host data of that run.

TYPE: dict[str, Tensor] | None DEFAULT: None

rank

Number of correlated directions. Default 5.

TYPE: int DEFAULT: 5

init_scale

Initial diagonal scale. W is initialized at zero.

TYPE: float DEFAULT: 0.1

Source code in src/quivers/inference/guides/multivariate_normal.py
def __init__(
    self,
    model: MonadicProgram,
    observed_names: set[str],
    rank: int = 5,
    init_scale: float = 0.1,
    *,
    x: torch.Tensor | None = None,
    observations: dict[str, torch.Tensor] | None = None,
) -> None:
    super().__init__(model, observed_names, x=x, observations=observations)
    if rank < 1:
        raise ValueError(
            f"AutoLowRankMultivariateNormalGuide: rank must be >= 1, got {rank}"
        )
    if rank > self._D:
        raise ValueError(
            f"AutoLowRankMultivariateNormalGuide: rank ({rank}) "
            f"cannot exceed total unconstrained dimension "
            f"({self._D})"
        )
    self._rank = rank
    init_diag = torch.full((self._D,), float(init_scale))
    init_diag_raw = torch.log(torch.expm1(init_diag.clamp(min=1e-6)))
    self.cov_diag_raw = nn.Parameter(init_diag_raw)
    self.cov_factor = nn.Parameter(torch.zeros(self._D, rank))

AutoMultivariateNormalGuide

AutoMultivariateNormalGuide(model: MonadicProgram, observed_names: set[str], init_scale: float = 0.1, *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None)

Bases: _MVNCommon

Full-rank multivariate-Normal variational guide.

Parameterises a joint Gaussian over the registry's flat unconstrained vector with a learnable lower-triangular Cholesky factor. Captures every pairwise posterior correlation across every latent site, the right choice when posterior couplings are strong (hierarchical regression with crossed random effects, parameter pairs with multiplicative interaction).

PARAMETER DESCRIPTION
model

Generative model to build a guide for.

TYPE: MonadicProgram

observed_names

Variable names treated as observations.

TYPE: set[str]

x

Keyword-only. A program input at which to build the latent registry from a run, required for a program that scans or calls a program that draws, whose latent sites depend on its input.

TYPE: Tensor | None DEFAULT: None

observations

Keyword-only. The observed values and host data of that run.

TYPE: dict[str, Tensor] | None DEFAULT: None

init_scale

Initial diagonal of the Cholesky factor. Default 0.1; the off-diagonal entries start at 0.

TYPE: float DEFAULT: 0.1

Source code in src/quivers/inference/guides/multivariate_normal.py
def __init__(
    self,
    model: MonadicProgram,
    observed_names: set[str],
    init_scale: float = 0.1,
    *,
    x: torch.Tensor | None = None,
    observations: dict[str, torch.Tensor] | None = None,
) -> None:
    super().__init__(model, observed_names, x=x, observations=observations)
    init_diag = torch.full((self._D,), float(init_scale))
    init_diag_raw = torch.log(torch.expm1(init_diag.clamp(min=1e-6)))
    self.scale_diag_raw = nn.Parameter(init_diag_raw)
    self.scale_offdiag = nn.Parameter(torch.zeros(self._D, self._D))

AutoNormalGuide

AutoNormalGuide(model: MonadicProgram, observed_names: set[str], init_scale: float = 0.1, *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None, initial_values: Mapping[str, Tensor | float] | None = None)

Bases: Guide

Mean-field Normal guide with per-site constrained-support bijector.

PARAMETER DESCRIPTION
model

Generative model to build a guide for.

TYPE: MonadicProgram

observed_names

Variable names treated as observations (skipped in the guide; their values flow through the conditioning data dict at trace time).

TYPE: set[str]

x

Keyword-only. A program input at which to build the latent registry from a run, required for a program that scans or calls a program that draws, whose latent sites depend on its input.

TYPE: Tensor | None DEFAULT: None

observations

Keyword-only. The observed values and host data of that run.

TYPE: dict[str, Tensor] | None DEFAULT: None

init_scale

Initial scale (in unconstrained space) of every latent. Default 0.1; small enough to keep the guide near its prior at the start of optimisation.

TYPE: float DEFAULT: 0.1

initial_values

Optional natural-scale initial centers keyed by latent site. Scalars broadcast to a site's shape; arrays must match it. Values must be strictly inside the site's support. Other centers remain zero in unconstrained space.

TYPE: Mapping[str, Tensor or float] or None DEFAULT: None

Notes

The guide factors over a plate's rows, so under a subsample block log_prob scores a latent in a subsampled plate at the subset's rows, times the same factor the model's sites take; every row is still drawn, and the rows outside the subset receive no gradient from the step.

Source code in src/quivers/inference/guides/normal.py
def __init__(
    self,
    model: MonadicProgram,
    observed_names: set[str],
    init_scale: float = 0.1,
    *,
    x: torch.Tensor | None = None,
    observations: dict[str, torch.Tensor] | None = None,
    initial_values: Mapping[str, torch.Tensor | float] | None = None,
) -> None:
    super().__init__()
    registry = self.build_registry(
        model, observed_names, x=x, observations=observations
    )
    self._initialize_registry(registry, init_scale, initial_values)

latent_names property

latent_names: list[str]

Return checked latent names in their registry order.

RETURNS DESCRIPTION
list[str]

Site labels, including individual scan occurrences.

from_registry classmethod

from_registry(registry: LatentRegistry, *, init_scale: float = 0.1, initial_values: Mapping[str, Tensor | float] | None = None) -> AutoNormalGuide

Initialize parameters against an already checked latent registry.

PARAMETER DESCRIPTION
registry

Existing model, site supports, and declared event geometry.

TYPE: LatentRegistry

init_scale

Initial unconstrained Normal scale, as in the ordinary constructor.

TYPE: float DEFAULT: 0.1

initial_values

Optional natural-scale parameter centers.

TYPE: Mapping[str, Tensor or float] or None DEFAULT: None

RETURNS DESCRIPTION
AutoNormalGuide

A fresh guide without tracing or sampling the model.

Source code in src/quivers/inference/guides/normal.py
@classmethod
def from_registry(
    cls,
    registry: LatentRegistry,
    *,
    init_scale: float = 0.1,
    initial_values: Mapping[str, torch.Tensor | float] | None = None,
) -> AutoNormalGuide:
    """Initialize parameters against an already checked latent registry.

    Parameters
    ----------
    registry : LatentRegistry
        Existing model, site supports, and declared event geometry.
    init_scale : float
        Initial unconstrained Normal scale, as in the ordinary constructor.
    initial_values : Mapping[str, torch.Tensor or float] or None
        Optional natural-scale parameter centers.

    Returns
    -------
    AutoNormalGuide
        A fresh guide without tracing or sampling the model.
    """
    guide = cls.__new__(cls)
    nn.Module.__init__(guide)
    guide._initialize_registry(registry, init_scale, initial_values)
    return guide

rsample

rsample(x: Tensor) -> dict[str, Tensor]

Draw a reparameterized mean-field Normal-then-bijector sample.

PARAMETER DESCRIPTION
x

Execution input whose leading axis gives the number of runs.

TYPE: Tensor

RETURNS DESCRIPTION
dict[str, Tensor]

Values indexed by checked latent names.

Source code in src/quivers/inference/guides/normal.py
def rsample(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
    """Draw a reparameterized mean-field Normal-then-bijector sample.

    Parameters
    ----------
    x : torch.Tensor
        Execution input whose leading axis gives the number of runs.

    Returns
    -------
    dict[str, torch.Tensor]
        Values indexed by checked latent names.
    """
    batch = x.shape[0]
    result: dict[str, torch.Tensor] = {}
    for site in self._registry.sites.values():
        _, v = self._sample_site(site, batch)
        result[site.name] = v
    return result

log_prob

log_prob(x: Tensor, sites: dict[str, Tensor]) -> Tensor

Pushforward log-density of each run's constrained values.

Uses the change-of-variables identity, run by run:

log q(v_b) = log Normal(z_b; loc, scale) + log|det J_{T^{-1}}(v_b)|

where z_b = bijector.inv(v_b) is read from LatentRegistry.unconstrain_runs. A latent in a plate that a subsample block is active for is scored at the subset's rows, times the plate's size over the subset's.

PARAMETER DESCRIPTION
x

Execution input carrying the leading run axis.

TYPE: Tensor

sites

Constrained latent values to score, each one per run or one the runs share (Guide.log_prob).

TYPE: dict[str, Tensor]

RETURNS DESCRIPTION
Tensor

One variational log density per execution run.

RAISES DESCRIPTION
KeyError

If a latent site is missing from sites.

ValueError

If a value is neither one per run nor one the runs share.

Source code in src/quivers/inference/guides/normal.py
def log_prob(
    self,
    x: torch.Tensor,
    sites: dict[str, torch.Tensor],
) -> torch.Tensor:
    """Pushforward log-density of each run's constrained values.

    Uses the change-of-variables identity, run by run:

        log q(v_b) = log Normal(z_b; loc, scale) + log|det J_{T^{-1}}(v_b)|

    where ``z_b = bijector.inv(v_b)`` is read from
    `LatentRegistry.unconstrain_runs`. A latent in a plate that a
    [`subsample`][quivers.effects.subsample] block is active for is
    scored at the subset's rows, times the plate's size over the
    subset's.

    Parameters
    ----------
    x : torch.Tensor
        Execution input carrying the leading run axis.
    sites : dict[str, torch.Tensor]
        Constrained latent values to score, each one per run or one
        the runs share (`Guide.log_prob`).

    Returns
    -------
    torch.Tensor
        One variational log density per execution run.

    Raises
    ------
    KeyError
        If a latent site is missing from ``sites``.
    ValueError
        If a value is neither one per run nor one the runs share.
    """
    runs = int(x.shape[0])
    coordinates = self._registry.unconstrain_runs(sites, runs)
    total = torch.zeros(runs, device=x.device)
    for site in self._registry.sites.values():
        z = coordinates.unconstrained[site.name]
        log_q_z = D.Normal(self._loc(site.name), self._scale(site.name)).log_prob(z)
        terms = log_q_z.sum(-1) + coordinates.log_abs_det[site.name]
        if site.is_plate:
            terms = self._plate_run_totals(site, terms)
        total = total + terms
    return total

Latent registry

Every guide and MCMC kernel reads the model's latent sites through a LatentRegistry.

registry

Latent-site registry: the canonical introspection surface that every variational guide and MCMC kernel consumes.

A LatentRegistry is built once from a quivers.continuous.programs.MonadicProgram and a set of observed site names. It walks the model's steps linear IR exactly once, classifies each latent into "plate" vs "scalar", records the prior support and per-site dimensionality, builds the matching torch.distributions.transforms.Transform via torch.distributions.constraint_registry.biject_to, and caches a fused flatten / unflatten pipeline so a single unconstrained vector can be turned into a fully constrained site dict (and back) in one pass.

The registry is the only place in the inference layer that knows about PlateDraw, the layout of MonadicProgram.steps, or the per-site constraint-to-bijector mapping. Every downstream component (Guide, MCMCKernel, the flow-based / structured / mixture guides) receives a fully populated registry and operates against its flat-vector and per-site dict APIs.

Categorical interpretation

Each latent site corresponds to a draw in the model's Kleisli arrow Γ → 𝒢(τ). The site's prior is a parameterized family F : Θ → 𝒢(B) with a support constraint C ⊆ B. The bijector T : ℝ^d → C is the biject_to lift of C; its log-determinant gives the change-of-variables term in any pushforward density.

For a plate v : A → B the latent lives in C^|A|; the registry handles the leading plate axis (size |A|) separately from the trailing event axis (the support dimension), and the unconstrained flat vector concatenates plate × event across every site in declaration order.

ReducedSupport

Bases: Protocol

A support with fewer free coordinates than its constrained vector.

unconstrained_dim

unconstrained_dim(constrained_dim: int) -> int

Count the free coordinates of a constrained vector.

PARAMETER DESCRIPTION
constrained_dim

Length of the constrained vector.

TYPE: int

RETURNS DESCRIPTION
int

Number of free coordinates.

Source code in src/quivers/inference/registry.py
def unconstrained_dim(self, constrained_dim: int) -> int:
    """Count the free coordinates of a constrained vector.

    Parameters
    ----------
    constrained_dim : int
        Length of the constrained vector.

    Returns
    -------
    int
        Number of free coordinates.
    """
    ...

LatentSite didactic-model

LatentSite(*, name: str, morphism: ContinuousMorphism = field(opaque=True, extras=OPAQUE_BY_IDENTITY), support: Constraint = field(opaque=True, extras=OPAQUE_BY_IDENTITY), bijector: Transform = field(opaque=True, extras=OPAQUE_BY_IDENTITY), constrained_dim: int, unconstrained_dim: int, is_plate: bool, plate_index_size: int, spec_index: int, flat_offset: int, flat_length: int, plate_shape: tuple[int, ...] = (), event_shape: tuple[int, ...] = ())

Bases: ValueModel

Frozen record describing a single latent site.

ATTRIBUTE DESCRIPTION
name

Variable name (the bound name in the program body).

TYPE: str

morphism

The site's runtime morphism (the prior). Held by reference so guides / kernels can call morphism.log_prob directly when they need the per-site prior contribution.

TYPE: ContinuousMorphism

support

Support of the prior. Drives the choice of bijector.

TYPE: Constraint

bijector

biject_to(support), cached at registry construction.

TYPE: Transform

constrained_dim

Event dimension on the constrained side (for a scalar site, 1; for a Dirichlet on a 5-simplex, 5).

TYPE: int

unconstrained_dim

Event dimension on the unconstrained side (for a Dirichlet on a 5-simplex, 4; otherwise equals constrained_dim).

TYPE: int

is_plate

Whether this site is a plate draw (PlateDraw).

TYPE: bool

plate_index_size

|A| for a plate site, 0 otherwise.

TYPE: int

spec_index

Position in model.steps.

TYPE: int

flat_offset

Index of this site's first element in the registry's flat unconstrained vector.

TYPE: int

flat_length

Number of elements this site occupies in the flat vector (= plate_index_size * unconstrained_dim for plate sites, unconstrained_dim for scalar sites).

TYPE: int

plate_shape

The extents of a plate site's axes, outermost first, whose product is plate_index_size: (|A|,) for a plate over one axis, (|A|, |B|, |C|) for an independent array over several; () otherwise.

TYPE: tuple[int, ...]

event_shape

Declared intrinsic event axes, including rectangular matrix events. Empty retains the legacy scalar/support-derived geometry.

TYPE: tuple[int, ...]

is_scalar property

is_scalar: bool

Whether one constrained event is a scalar, rather than a singleton tensor.

RETURNS DESCRIPTION
bool

True only for a one-coordinate support without intrinsic event axes. Singleton simplices and matrices retain their event axes.

constrained_shape property

constrained_shape: tuple[int, ...]

The shape of one draw of this site on its constrained support after the bijector. Scalar supports omit an event axis; singleton simplex and matrix supports retain theirs.

Plate sites have shape (*plate_shape,) or (*plate_shape, d), (|A|,) or (|A|, d) for a plate over one axis; non-plate sites have shape () for a scalar event and (d,) otherwise. Posterior containers index draws by this shape: MCMCResult.samples holds (num_chains, num_samples, *constrained_shape) and MCMCResult.r_hat and MCMCResult.ess hold constrained_shape.

The values a program's MonadicProgram.log_joint, a trace, and a guide exchange carry the run axis of the program's input, whose B rows are B independent runs: a non-plate site is (B, *constrained_shape) ((1, *constrained_shape) in one run), and a plate site is constrained_shape in one run, or one value every run shares, and (B, *constrained_shape) given or recorded per run. LatentRegistry.trace_values lifts one draw to the values runs share.

A correlation-Cholesky site's draw is a lower-triangular (d, d) factor and a positive-definite site's a (d, d) matrix, so its event shape is (d, d) rather than (d,).

unconstrained_shape property

unconstrained_shape: tuple[int, ...]

The variational-side shape of this site's value in unconstrained space (before the bijector).

constrain

constrain(value: Tensor) -> tuple[Tensor, Tensor]

Map flat site coordinates to the declared structured event.

PARAMETER DESCRIPTION
value

Site unconstrained coordinates, optionally preceded by sample/run axes.

TYPE: Tensor

RETURNS DESCRIPTION
tuple[Tensor, Tensor]

Structured constrained values and the transform-native log Jacobian. Only support event axes are reduced by an event-aware transform.

RAISES DESCRIPTION
ValueError

If the trailing coordinates disagree with the declared site layout.

Source code in src/quivers/inference/registry.py
def constrain(self, value: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
    """Map flat site coordinates to the declared structured event.

    Parameters
    ----------
    value : torch.Tensor
        Site unconstrained coordinates, optionally preceded by sample/run axes.

    Returns
    -------
    tuple[torch.Tensor, torch.Tensor]
        Structured constrained values and the transform-native log Jacobian.
        Only support event axes are reduced by an event-aware transform.

    Raises
    ------
    ValueError
        If the trailing coordinates disagree with the declared site layout.
    """
    width = len(self.unconstrained_shape)
    if tuple(value.shape[-width:]) != self.unconstrained_shape:
        raise ValueError(
            f"unconstrained site {self.name!r} requires trailing shape {self.unconstrained_shape}"
        )
    leading = value.shape[:-width]
    transform_shape = (
        self.unconstrained_shape
        if self.is_scalar
        else self.bijector.inverse_shape(torch.Size(self.constrained_shape))
    )
    structured = value.reshape((*leading, *transform_shape))
    result = _apply_transform(self.bijector, structured)
    log_det = self.bijector.log_abs_det_jacobian(structured, result)
    return result.reshape((*leading, *self.constrained_shape)), log_det

unconstrain

unconstrain(value: Tensor) -> tuple[Tensor, Tensor]

Invert a declared structured event into flat site coordinates.

PARAMETER DESCRIPTION
value

Constrained event, optionally preceded by sample/run axes.

TYPE: Tensor

RETURNS DESCRIPTION
tuple[Tensor, Tensor]

Flat site coordinates and the transform-native inverse log Jacobian.

RAISES DESCRIPTION
ValueError

If the event's trailing axes disagree with its declared shape.

Source code in src/quivers/inference/registry.py
def unconstrain(self, value: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
    """Invert a declared structured event into flat site coordinates.

    Parameters
    ----------
    value : torch.Tensor
        Constrained event, optionally preceded by sample/run axes.

    Returns
    -------
    tuple[torch.Tensor, torch.Tensor]
        Flat site coordinates and the transform-native inverse log Jacobian.

    Raises
    ------
    ValueError
        If the event's trailing axes disagree with its declared shape.
    """
    width = len(self.constrained_shape)
    if width and tuple(value.shape[-width:]) != self.constrained_shape:
        raise ValueError(
            f"constrained site {self.name!r} requires trailing shape {self.constrained_shape}"
        )
    leading = value.shape[:-width] if width else value.shape
    structured = (
        value.reshape((*leading, *self.unconstrained_shape))
        if self.is_scalar
        else value
    )
    result = _apply_transform(self.bijector.inv, structured)
    log_det = self.bijector.inv.log_abs_det_jacobian(structured, result)
    return result.reshape((*leading, *self.unconstrained_shape)), log_det

align_runs

align_runs(value: Tensor, runs: int) -> Tensor

Give a trace-side value of this site one entry per run.

The values a program's log joint, a trace, and a guide exchange for an input of runs rows take one of two shapes. A value of shape (runs, *constrained_shape) holds one value per run, run b at index b. A value of shape constrained_shape has no run axis and is one value every run shares, as a plate latent drawn once is. No other shape is a value of the site: in particular a run axis of size one does not stand for runs runs.

PARAMETER DESCRIPTION
value

The site's value, shared by every run or given per run.

TYPE: Tensor

runs

The number of runs, the rows of the program input.

TYPE: int

RETURNS DESCRIPTION
Tensor

Shape (runs, *constrained_shape); a shared value is expanded along the new run axis without a copy.

RAISES DESCRIPTION
ValueError

If runs is less than one, or value has neither shape.

Source code in src/quivers/inference/registry.py
def align_runs(self, value: torch.Tensor, runs: int) -> torch.Tensor:
    """Give a trace-side value of this site one entry per run.

    The values a program's log joint, a trace, and a guide exchange
    for an input of ``runs`` rows take one of two shapes. A value of
    shape ``(runs, *constrained_shape)`` holds one value per run,
    run ``b`` at index ``b``. A value of shape `constrained_shape`
    has no run axis and is one value every run shares, as a plate
    latent drawn once is. No other shape is a value of the site:
    in particular a run axis of size one does not stand for
    ``runs`` runs.

    Parameters
    ----------
    value : torch.Tensor
        The site's value, shared by every run or given per run.
    runs : int
        The number of runs, the rows of the program input.

    Returns
    -------
    torch.Tensor
        Shape ``(runs, *constrained_shape)``; a shared value is
        expanded along the new run axis without a copy.

    Raises
    ------
    ValueError
        If ``runs`` is less than one, or ``value`` has neither
        shape.
    """
    if runs < 1:
        raise ValueError(
            f"LatentSite.align_runs: runs must be >= 1, got {runs} for site "
            f"{self.name!r}"
        )
    shape = self.constrained_shape
    if tuple(value.shape) == shape:
        return value.unsqueeze(0).expand(runs, *shape)
    if value.dim() == len(shape) + 1 and tuple(value.shape[1:]) == shape:
        if value.shape[0] == runs:
            return value
        raise ValueError(
            f"site {self.name!r} has a run axis of {value.shape[0]} values for "
            f"an input of {runs} runs; give one value per run, "
            f"({runs}, *{shape}), or one value the runs share, {shape}"
        )
    raise ValueError(
        f"site {self.name!r} has shape {tuple(value.shape)}; a value of it is "
        f"one per run, ({runs}, *{shape}), or one the runs share, {shape}"
    )

unconstrain_runs

unconstrain_runs(value: Tensor, runs: int) -> tuple[Tensor, Tensor]

Map a trace-side value to unconstrained coordinates, run by run.

The value is aligned to the run axis (align_runs) and passed through the inverse bijector. The inverse Jacobian term is summed over each element's event axes and kept apart for every run and, for a plate site, every plate element, so a guide can score each run alone and each plate row alone.

PARAMETER DESCRIPTION
value

The site's value, shared by every run or given per run.

TYPE: Tensor

runs

The number of runs.

TYPE: int

RETURNS DESCRIPTION
tuple[Tensor, Tensor]

The coordinates, shape (runs, *unconstrained_shape), and :math:\log |\det J_{T^{-1}}| of each run's value, shape (runs,), or (runs, plate_index_size) for a plate site with the plate's elements in row-major order.

RAISES DESCRIPTION
ValueError

If the value is not a value of the site, or the bijector's Jacobian term does not keep the run axis and the plate's elements apart.

Source code in src/quivers/inference/registry.py
def unconstrain_runs(
    self, value: torch.Tensor, runs: int
) -> tuple[torch.Tensor, torch.Tensor]:
    """Map a trace-side value to unconstrained coordinates, run by run.

    The value is aligned to the run axis (`align_runs`) and passed
    through the inverse bijector. The inverse Jacobian term is
    summed over each element's event axes and kept apart for every
    run and, for a plate site, every plate element, so a guide can
    score each run alone and each plate row alone.

    Parameters
    ----------
    value : torch.Tensor
        The site's value, shared by every run or given per run.
    runs : int
        The number of runs.

    Returns
    -------
    tuple[torch.Tensor, torch.Tensor]
        The coordinates, shape ``(runs, *unconstrained_shape)``, and
        :math:`\\log |\\det J_{T^{-1}}|` of each run's value, shape
        ``(runs,)``, or ``(runs, plate_index_size)`` for a plate site
        with the plate's elements in row-major order.

    Raises
    ------
    ValueError
        If the value is not a value of the site, or the bijector's
        Jacobian term does not keep the run axis and the plate's
        elements apart.
    """
    z, log_det = self.unconstrain(self.align_runs(value, runs))
    elements = self.plate_index_size if self.is_plate else 1
    if (
        log_det.dim() == 0
        or log_det.shape[0] != runs
        or log_det.numel() % (runs * elements)
    ):
        raise ValueError(
            f"site {self.name!r}: the bijector's Jacobian term has shape "
            f"{tuple(log_det.shape)}, which does not hold one term per run "
            f"and per plate element for {runs} runs of {elements} elements"
        )
    per_element = log_det.reshape(runs, elements, -1).sum(-1)
    if not self.is_plate:
        per_element = per_element.reshape(runs)
    return z, per_element

RunCoordinates didactic-model

RunCoordinates(*, runs: int, unconstrained: dict[str, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), log_abs_det: dict[str, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

The latent values of several runs in unconstrained coordinates.

Built by LatentRegistry.unconstrain_runs, which applies LatentSite.unconstrain_runs to every site.

PARAMETER DESCRIPTION
runs

The number of runs.

TYPE: int

unconstrained

Each site's coordinates, shape (runs, *unconstrained_shape), in registry order.

TYPE: dict[str, Tensor] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

log_abs_det

Each site's inverse-bijector term :math:\log |\det J_{T^{-1}}| per run, shape (runs,), or (runs, plate_index_size) for a plate site.

TYPE: dict[str, Tensor] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

total_log_abs_det

total_log_abs_det() -> Tensor

The inverse-bijector term of each run, summed over its sites.

RETURNS DESCRIPTION
Tensor

Shape (runs,): entry b is :math:\sum_i \log |\det J_{T_i^{-1}}(v_{b,i})|.

Source code in src/quivers/inference/registry.py
def total_log_abs_det(self) -> torch.Tensor:
    """The inverse-bijector term of each run, summed over its sites.

    Returns
    -------
    torch.Tensor
        Shape ``(runs,)``: entry ``b`` is
        :math:`\\sum_i \\log |\\det J_{T_i^{-1}}(v_{b,i})|`.
    """
    total = torch.zeros(self.runs)
    for terms in self.log_abs_det.values():
        total = total.to(terms) + terms.reshape(self.runs, -1).sum(-1)
    return total

LatentRegistry

LatentRegistry(sites: dict[str, LatentSite], observed_names: frozenset[str], model: MonadicProgram)

The complete introspection result for one (model, observed-set) pair.

Constructed once via from_model; immutable thereafter. Provides:

  • Iteration over latent sites in declaration order (sites, plate_sites, scalar_sites).
  • Total unconstrained dimensionality (total_unconstrained_dim), the dim of the flat vector HMC and full-rank Gaussian guides operate on.
  • Round-tripping between a flat unconstrained vector and a dict of constrained per-site tensors (unflatten_unconstrained, flatten_constrained).
  • Bijector forward / inverse with Jacobian accumulation (to_constrained, to_unconstrained).
  • Conversion between one draw per site, at LatentSite.constrained_shape, and the trace-side values a program's log_joint and the guides exchange, which add the (batch, ...) axis to non-plate sites (trace_values, trace_row).

All operations are vectorized, with no per-site Python loops on the hot path beyond the construction-time setup.

Source code in src/quivers/inference/registry.py
def __init__(
    self,
    sites: dict[str, LatentSite],
    observed_names: frozenset[str],
    model: MonadicProgram,
) -> None:
    self._sites: dict[str, LatentSite] = sites
    self._observed_names: frozenset[str] = observed_names
    self._model: MonadicProgram = model
    self._total_unconstrained_dim: int = sum(s.flat_length for s in sites.values())

sites property

sites: dict[str, LatentSite]

Every latent site, keyed by name, in declaration order.

plate_sites property

plate_sites: dict[str, LatentSite]

The subset of sites that are PlateDraw-shaped.

scalar_sites property

scalar_sites: dict[str, LatentSite]

The subset of sites that are not plates.

names property

names: tuple[str, ...]

Latent site names in declaration order.

observed_names property

observed_names: frozenset[str]

The observed-name set used to build this registry.

model property

The underlying model.

total_unconstrained_dim property

total_unconstrained_dim: int

Sum of every site's flat-vector length.

This is the dim of the unconstrained vector that full-rank Gaussian guides and HMC operate on.

from_model classmethod

from_model(model: MonadicProgram, observed_names: set[str] | frozenset[str]) -> 'LatentRegistry'

Walk model.steps and assemble the registry.

PARAMETER DESCRIPTION
model

Compiled probabilistic program.

TYPE: MonadicProgram

observed_names

Variable names treated as observations. Sample sites with names in this set are skipped (their values come from the conditioning data dict at trace time, not from a guide). An observation of an earlier lexical binding is also skipped: its value is computed by the model, rather than supplied by a guide.

TYPE: set[str] | frozenset[str]

RETURNS DESCRIPTION
LatentRegistry

Fully populated registry with each latent's morphism, support, bijector, dims, and flat-vector offsets.

Source code in src/quivers/inference/registry.py
@classmethod
def from_model(
    cls,
    model: MonadicProgram,
    observed_names: set[str] | frozenset[str],
) -> "LatentRegistry":
    """Walk ``model.steps`` and assemble the registry.

    Parameters
    ----------
    model : MonadicProgram
        Compiled probabilistic program.
    observed_names : set[str] | frozenset[str]
        Variable names treated as observations. Sample sites
        with names in this set are skipped (their values come
        from the conditioning data dict at trace time, not
        from a guide). An observation of an earlier lexical binding
        is also skipped: its value is computed by the model, rather
        than supplied by a guide.

    Returns
    -------
    LatentRegistry
        Fully populated registry with each latent's morphism,
        support, bijector, dims, and flat-vector offsets.
    """
    observed: frozenset[str] = frozenset(observed_names)
    if _input_dependent_sites(model):
        raise ValueError(
            "LatentRegistry.from_model: the program's steps do not list its "
            "sites (it runs a checked computation, or scans or calls a "
            "program that draws), so how many latent sites it has depends "
            "on its input; build the registry from a run with "
            "LatentRegistry.from_trace(model, trace(model, x, observations))"
        )
    sites: dict[str, LatentSite] = {}
    flat_cursor = 0
    bound = set(model._params or ())
    computed_observed: set[str] = set()

    for spec_idx, spec in enumerate(model.steps):
        if isinstance(spec, Let | Score | Call | Scan):
            bound.add(spec.name)
            continue
        if not isinstance(spec, Draw | Observe):
            continue
        for var in spec.names:
            if var in observed or isinstance(spec, Observe) and var in bound:
                if var not in sites:
                    computed_observed.add(var)
                continue
            morph = model.step_module(spec)
            if morph is None:
                raise RuntimeError(
                    f"LatentRegistry: morphism module for site "
                    f"{var!r} is unregistered on the model"
                )
            site = _latent_site(
                var,
                cast(ContinuousMorphism, morph),
                len(spec.names),
                spec_idx,
                flat_cursor,
            )
            sites[var] = site
            flat_cursor += site.flat_length
        bound.update(spec.names)

    return cls(sites, observed | computed_observed, model)

from_trace classmethod

from_trace(model: MonadicProgram, recorded: Trace, *, exclude: frozenset[str] | set[str] = frozenset()) -> 'LatentRegistry'

Assemble the registry from a run of the model.

Every sample site the run reached that is neither observed nor intervened on is a latent, in the order the run reached it. A site a scan reaches once per position is one latent per position, "<label>@<n>", so a scanned program cell's latent trajectory is inferred site by site, as many as the input's sequence has positions. Build recorded with trace(model, x, observations) at the input and data the latents are inferred at.

Sites named in exclude are left out: they are latent, but held outside the flat vector, as the sites a GibbsKernel updates are, and they need not have a support the registry can biject onto (a discrete site, for instance).

PARAMETER DESCRIPTION
model

Compiled probabilistic program.

TYPE: MonadicProgram

recorded

A trace of one run of model.

TYPE: Trace

exclude

Latent sites to leave out of the registry.

TYPE: frozenset[str] | set[str] DEFAULT: frozenset()

RETURNS DESCRIPTION
LatentRegistry

Fully populated registry with each admitted latent's morphism, support, bijector, dims, and flat-vector offsets.

RAISES DESCRIPTION
ValueError

If a structured latent is neither observed nor explicitly excluded. A finite term has no Euclidean coordinates for this registry's continuous estimators.

Source code in src/quivers/inference/registry.py
@classmethod
def from_trace(
    cls,
    model: MonadicProgram,
    recorded: Trace,
    *,
    exclude: frozenset[str] | set[str] = frozenset(),
) -> "LatentRegistry":
    """Assemble the registry from a run of the model.

    Every sample site the run reached that is neither observed nor
    intervened on is a latent, in the order the run reached it. A
    site a scan reaches once per position is one latent per
    position, ``"<label>@<n>"``, so a scanned program cell's latent
    trajectory is inferred site by site, as many as the input's
    sequence has positions. Build ``recorded`` with
    ``trace(model, x, observations)`` at the input and data the
    latents are inferred at.

    Sites named in ``exclude`` are left out: they are latent, but
    held outside the flat vector, as the sites a `GibbsKernel`
    updates are, and they need not have a support the registry can
    biject onto (a discrete site, for instance).

    Parameters
    ----------
    model : MonadicProgram
        Compiled probabilistic program.
    recorded : Trace
        A trace of one run of ``model``.
    exclude : frozenset[str] | set[str]
        Latent sites to leave out of the registry.

    Returns
    -------
    LatentRegistry
        Fully populated registry with each admitted latent's morphism,
        support, bijector, dims, and flat-vector offsets.

    Raises
    ------
    ValueError
        If a structured latent is neither observed nor explicitly
        excluded. A finite term has no Euclidean coordinates for this
        registry's continuous estimators.
    """
    reached = _reaching_steps(model)
    sites: dict[str, LatentSite] = {}
    observed: set[str] = set()
    flat_cursor = 0
    for label, record in recorded.sites.items():
        if record.is_deterministic:
            continue
        if record.is_structured:
            if record.is_observed:
                observed.add(label)
            elif label not in exclude:
                raise ValueError(
                    f"structured latent {label!r} cannot enter a continuous latent registry; "
                    "condition or exactly enumerate the site, or exclude it explicitly"
                )
            continue
        if record.morphism is None:
            continue
        if record.is_observed:
            observed.update(label.split(","))
            continue
        names = label.split(",")
        if label in exclude or any(name in exclude for name in names):
            continue
        base = label.rpartition("@")[0] or label
        spec_index = reached.get(base.split(",")[0], -1)
        for var in names:
            site = _latent_site(
                var if len(names) > 1 else label,
                record.morphism,
                len(names),
                spec_index,
                flat_cursor,
            )
            sites[site.name] = site
            flat_cursor += site.flat_length
    return cls(sites, frozenset(observed), model)

unflatten_unconstrained

unflatten_unconstrained(vec: Tensor) -> dict[str, Tensor]

Reshape a flat unconstrained vector into per-site unconstrained tensors.

PARAMETER DESCRIPTION
vec

Shape (..., total_unconstrained_dim). Leading axes (batch, particles, chains) are preserved on every site's output.

TYPE: Tensor

RETURNS DESCRIPTION
dict[str, Tensor]

{name: site_tensor} where each site_tensor has shape vec.shape[:-1] + site.unconstrained_shape.

Source code in src/quivers/inference/registry.py
def unflatten_unconstrained(self, vec: torch.Tensor) -> dict[str, torch.Tensor]:
    """Reshape a flat unconstrained vector into per-site
    unconstrained tensors.

    Parameters
    ----------
    vec : torch.Tensor
        Shape ``(..., total_unconstrained_dim)``. Leading
        axes (batch, particles, chains) are preserved on every
        site's output.

    Returns
    -------
    dict[str, torch.Tensor]
        ``{name: site_tensor}`` where each ``site_tensor`` has
        shape ``vec.shape[:-1] + site.unconstrained_shape``.
    """
    if vec.shape[-1] != self._total_unconstrained_dim:
        raise ValueError(
            f"LatentRegistry.unflatten_unconstrained: expected "
            f"trailing dim {self._total_unconstrained_dim}, got "
            f"{vec.shape[-1]}"
        )
    out: dict[str, torch.Tensor] = {}
    for site in self._sites.values():
        chunk = vec[..., site.flat_offset : site.flat_offset + site.flat_length]
        out[site.name] = chunk.reshape(*vec.shape[:-1], *site.unconstrained_shape)
    return out

flatten_unconstrained

flatten_unconstrained(sites: dict[str, Tensor]) -> Tensor

Concatenate per-site unconstrained tensors into a single flat vector.

Inverse of unflatten_unconstrained (up to leading batch axes). The trailing batch axes of every site tensor must agree.

Source code in src/quivers/inference/registry.py
def flatten_unconstrained(self, sites: dict[str, torch.Tensor]) -> torch.Tensor:
    """Concatenate per-site unconstrained tensors into a single
    flat vector.

    Inverse of `unflatten_unconstrained` (up to leading
    batch axes). The trailing batch axes of every site tensor
    must agree.
    """
    parts: list[torch.Tensor] = []
    leading_shape: tuple[int, ...] | None = None
    for site in self._sites.values():
        if site.name not in sites:
            raise KeyError(
                f"LatentRegistry.flatten_unconstrained: missing site {site.name!r}"
            )
        t = sites[site.name]
        trail = len(site.unconstrained_shape)
        site_leading = t.shape[: t.dim() - trail] if trail else t.shape
        if leading_shape is None:
            leading_shape = tuple(site_leading)
        elif tuple(site_leading) != leading_shape:
            raise ValueError(
                f"LatentRegistry.flatten_unconstrained: site "
                f"{site.name!r} has leading shape {tuple(site_leading)} "
                f"which disagrees with previously-seen "
                f"{leading_shape}"
            )
        parts.append(t.reshape(*site_leading, site.flat_length))
    if not parts:
        device = next(iter(sites.values())).device if sites else torch.device("cpu")
        return torch.zeros((0,), device=device)
    return torch.cat(parts, dim=-1)

unconstrain_runs

unconstrain_runs(sites: dict[str, Tensor], runs: int) -> RunCoordinates

Map the trace-side values of runs runs to unconstrained coordinates.

This is the one place a guide reads site values per run. Each site's value is aligned to the run axis and inverted through its bijector (LatentSite.unconstrain_runs), so run b of the result depends only on run b of every value, or on a value the runs share. Every guide whose density is over the registry's coordinates scores sites from this result, and LatentRegistry.flatten_unconstrained of its coordinates is the (runs, total_unconstrained_dim) matrix whose row b is run b's flat point.

PARAMETER DESCRIPTION
sites

Trace-side values of every latent site; keys that name no latent site are ignored.

TYPE: dict[str, Tensor]

runs

The number of runs, the rows of the program input.

TYPE: int

RETURNS DESCRIPTION
RunCoordinates

Each site's coordinates and inverse-bijector terms, per run.

RAISES DESCRIPTION
KeyError

If a latent site is missing from sites.

ValueError

If a value is neither one per run nor one the runs share.

Source code in src/quivers/inference/registry.py
def unconstrain_runs(
    self, sites: dict[str, torch.Tensor], runs: int
) -> RunCoordinates:
    """Map the trace-side values of ``runs`` runs to unconstrained coordinates.

    This is the one place a guide reads site values per run. Each
    site's value is aligned to the run axis and inverted through
    its bijector (`LatentSite.unconstrain_runs`), so run ``b`` of
    the result depends only on run ``b`` of every value, or on a
    value the runs share. Every guide whose density is over the
    registry's coordinates scores ``sites`` from this result, and
    `LatentRegistry.flatten_unconstrained` of its coordinates is
    the ``(runs, total_unconstrained_dim)`` matrix whose row ``b``
    is run ``b``'s flat point.

    Parameters
    ----------
    sites : dict[str, torch.Tensor]
        Trace-side values of every latent site; keys that name no
        latent site are ignored.
    runs : int
        The number of runs, the rows of the program input.

    Returns
    -------
    RunCoordinates
        Each site's coordinates and inverse-bijector terms, per run.

    Raises
    ------
    KeyError
        If a latent site is missing from ``sites``.
    ValueError
        If a value is neither one per run nor one the runs share.
    """
    unconstrained: dict[str, torch.Tensor] = {}
    log_abs_det: dict[str, torch.Tensor] = {}
    for site in self._sites.values():
        if site.name not in sites:
            raise KeyError(
                f"LatentRegistry.unconstrain_runs: missing site {site.name!r}"
            )
        unconstrained[site.name], log_abs_det[site.name] = site.unconstrain_runs(
            sites[site.name], runs
        )
    return RunCoordinates(
        runs=runs, unconstrained=unconstrained, log_abs_det=log_abs_det
    )

to_constrained

to_constrained(unconstrained: dict[str, Tensor]) -> tuple[dict[str, Tensor], dict[str, Tensor]]

Push every site's unconstrained value through its bijector.

RETURNS DESCRIPTION
constrained

Per-site constrained values shaped according to LatentSite.constrained_shape. The trailing length-1 event axis of a scalar site is squeezed off to match the trace-side shape convention.

TYPE: dict[str, Tensor]

log_abs_dets

Per-site log |det dT/dz| returned by the bijector, at the bijector's natural shape (event axes preserved). Callers aggregate as the objective requires: for ELBO we sum over event axes; for IWAE we keep particles as a leading axis; etc.

TYPE: dict[str, Tensor]

Source code in src/quivers/inference/registry.py
def to_constrained(
    self, unconstrained: dict[str, torch.Tensor]
) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
    """Push every site's unconstrained value through its
    bijector.

    Returns
    -------
    constrained : dict[str, torch.Tensor]
        Per-site constrained values shaped according to
        `LatentSite.constrained_shape`. The trailing
        length-1 event axis of a scalar site is squeezed off
        to match the trace-side shape convention.
    log_abs_dets : dict[str, torch.Tensor]
        Per-site ``log |det dT/dz|`` returned by the bijector,
        at the bijector's natural shape (event axes preserved).
        Callers aggregate as the objective requires: for ELBO
        we sum over event axes; for IWAE we keep particles as
        a leading axis; etc.
    """
    constrained: dict[str, torch.Tensor] = {}
    log_abs_dets: dict[str, torch.Tensor] = {}
    for site in self._sites.values():
        if site.name not in unconstrained:
            raise KeyError(
                f"LatentRegistry.to_constrained: missing site {site.name!r}"
            )
        constrained[site.name], log_abs_dets[site.name] = site.constrain(
            unconstrained[site.name]
        )
    return constrained, log_abs_dets

to_unconstrained

to_unconstrained(constrained: dict[str, Tensor]) -> tuple[dict[str, Tensor], dict[str, Tensor]]

Inverse of to_constrained.

Source code in src/quivers/inference/registry.py
def to_unconstrained(
    self, constrained: dict[str, torch.Tensor]
) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
    """Inverse of `to_constrained`."""
    unconstrained: dict[str, torch.Tensor] = {}
    log_abs_dets: dict[str, torch.Tensor] = {}
    for site in self._sites.values():
        if site.name not in constrained:
            raise KeyError(
                f"LatentRegistry.to_unconstrained: missing site {site.name!r}"
            )
        unconstrained[site.name], log_abs_dets[site.name] = site.unconstrain(
            constrained[site.name]
        )
    return unconstrained, log_abs_dets

trace_values

trace_values(constrained: dict[str, Tensor], batch_size: int) -> dict[str, Tensor]

Lift single constrained draws to trace-side values.

A trace-side value is what MonadicProgram.log_joint, a trace, and Guide.rsample exchange: each non-plate site carries the program's leading batch axis, shape (batch_size, *constrained_shape), and each plate site keeps constrained_shape. The lift expands the one draw across the batch axis, so every input row sees the same latent value.

PARAMETER DESCRIPTION
constrained

One draw per latent site, each of shape LatentSite.constrained_shape (as in one entry of MCMCResult.samples or the output of to_constrained on an unbatched unconstrained vector). Keys that name no latent site are passed through unchanged.

TYPE: dict[str, Tensor]

batch_size

Size of the program input's leading batch axis.

TYPE: int

RETURNS DESCRIPTION
dict[str, Tensor]

The trace-side values, keyed as constrained.

RAISES DESCRIPTION
ValueError

If batch_size is less than one, or a latent site's value does not have shape LatentSite.constrained_shape.

Source code in src/quivers/inference/registry.py
def trace_values(
    self, constrained: dict[str, torch.Tensor], batch_size: int
) -> dict[str, torch.Tensor]:
    """Lift single constrained draws to trace-side values.

    A trace-side value is what `MonadicProgram.log_joint`, a
    trace, and `Guide.rsample` exchange: each non-plate site
    carries the program's leading batch axis, shape
    ``(batch_size, *constrained_shape)``, and each plate site
    keeps ``constrained_shape``. The lift expands the one draw
    across the batch axis, so every input row sees the same
    latent value.

    Parameters
    ----------
    constrained : dict[str, torch.Tensor]
        One draw per latent site, each of shape
        `LatentSite.constrained_shape` (as in one entry of
        `MCMCResult.samples` or the output of `to_constrained`
        on an unbatched unconstrained vector). Keys that name no
        latent site are passed through unchanged.
    batch_size : int
        Size of the program input's leading batch axis.

    Returns
    -------
    dict[str, torch.Tensor]
        The trace-side values, keyed as ``constrained``.

    Raises
    ------
    ValueError
        If ``batch_size`` is less than one, or a latent site's
        value does not have shape `LatentSite.constrained_shape`.
    """
    if batch_size < 1:
        raise ValueError(
            f"LatentRegistry.trace_values: batch_size must be >= 1, "
            f"got {batch_size}"
        )
    out: dict[str, torch.Tensor] = {}
    for name, value in constrained.items():
        site = self._sites.get(name)
        if site is None:
            out[name] = value
            continue
        if tuple(value.shape) != site.constrained_shape:
            raise ValueError(
                f"LatentRegistry.trace_values: site {name!r} has shape "
                f"{tuple(value.shape)}; expected its constrained shape "
                f"{site.constrained_shape}"
            )
        if site.is_plate:
            out[name] = value
        else:
            out[name] = value.unsqueeze(0).expand(batch_size, *value.shape)
    return out

trace_draw

trace_draw(run: Trace) -> dict[str, Tensor]

One draw per latent site, at its constrained shape, from a run.

A site a destructuring draw binds takes its share of the draw's value, split evenly along the last axis.

PARAMETER DESCRIPTION
run

A trace of one run of the model.

TYPE: Trace

RETURNS DESCRIPTION
dict[str, Tensor]

Each latent site's value at LatentSite.constrained_shape, detached from the run's graph.

RAISES DESCRIPTION
ValueError

If the run did not reach a latent site.

Source code in src/quivers/inference/registry.py
def trace_draw(self, run: Trace) -> dict[str, torch.Tensor]:
    """One draw per latent site, at its constrained shape, from a run.

    A site a destructuring draw binds takes its share of the draw's
    value, split evenly along the last axis.

    Parameters
    ----------
    run : Trace
        A trace of one run of the model.

    Returns
    -------
    dict[str, torch.Tensor]
        Each latent site's value at `LatentSite.constrained_shape`,
        detached from the run's graph.

    Raises
    ------
    ValueError
        If the run did not reach a latent site.
    """
    reached = _trace_latent_values(
        run, include_observed=True, selected=frozenset(self._sites)
    )
    out: dict[str, torch.Tensor] = {}
    for name, site in self._sites.items():
        value = reached.get(name)
        if value is None:
            raise ValueError(
                f"LatentRegistry.trace_draw: the run did not reach the latent "
                f"site {name!r}"
            )
        out[name] = value.reshape(site.constrained_shape)
    return out

trace_row

trace_row(trace_side: dict[str, Tensor], row: int = 0) -> dict[str, Tensor]

Read one draw per latent site out of trace-side values.

The inverse of trace_values for one batch row: each non-plate site, of shape (batch, *constrained_shape), contributes its row row, and each plate site, of shape constrained_shape, is returned as is. A guide's Guide.rsample output is a valid input.

PARAMETER DESCRIPTION
trace_side

Trace-side values for every latent site. Keys that name no latent site are ignored.

TYPE: dict[str, Tensor]

row

Index into the batch axis of the non-plate sites.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, Tensor]

One draw per latent site, each of shape LatentSite.constrained_shape, in declaration order.

RAISES DESCRIPTION
KeyError

If a latent site is missing from trace_side.

ValueError

If a site's value is not trace-side shaped, or row is outside a non-plate site's batch axis.

Source code in src/quivers/inference/registry.py
def trace_row(
    self, trace_side: dict[str, torch.Tensor], row: int = 0
) -> dict[str, torch.Tensor]:
    """Read one draw per latent site out of trace-side values.

    The inverse of `trace_values` for one batch row: each
    non-plate site, of shape ``(batch, *constrained_shape)``,
    contributes its row ``row``, and each plate site, of shape
    ``constrained_shape``, is returned as is. A guide's
    `Guide.rsample` output is a valid input.

    Parameters
    ----------
    trace_side : dict[str, torch.Tensor]
        Trace-side values for every latent site. Keys that name
        no latent site are ignored.
    row : int
        Index into the batch axis of the non-plate sites.

    Returns
    -------
    dict[str, torch.Tensor]
        One draw per latent site, each of shape
        `LatentSite.constrained_shape`, in declaration order.

    Raises
    ------
    KeyError
        If a latent site is missing from ``trace_side``.
    ValueError
        If a site's value is not trace-side shaped, or ``row`` is
        outside a non-plate site's batch axis.
    """
    out: dict[str, torch.Tensor] = {}
    for site in self._sites.values():
        if site.name not in trace_side:
            raise KeyError(f"LatentRegistry.trace_row: missing site {site.name!r}")
        value = trace_side[site.name]
        if site.is_plate:
            if tuple(value.shape) != site.constrained_shape:
                raise ValueError(
                    f"LatentRegistry.trace_row: plate site {site.name!r} "
                    f"has shape {tuple(value.shape)}; expected "
                    f"{site.constrained_shape}"
                )
            out[site.name] = value
            continue
        if value.dim() != len(site.constrained_shape) + 1 or (
            tuple(value.shape[1:]) != site.constrained_shape
        ):
            raise ValueError(
                f"LatentRegistry.trace_row: site {site.name!r} has shape "
                f"{tuple(value.shape)}; expected the trace-side shape "
                f"(batch, *{site.constrained_shape})"
            )
        if not 0 <= row < value.shape[0]:
            raise ValueError(
                f"LatentRegistry.trace_row: row {row} is outside the "
                f"batch axis of size {value.shape[0]} on site {site.name!r}"
            )
        out[site.name] = value[row]
    return out

aggregate_log_abs_det staticmethod

aggregate_log_abs_det(log_abs_dets: dict[str, Tensor], leading_shape: tuple[int, ...] = ()) -> Tensor

Sum every per-site log_abs_det over its event axes and produce a single tensor broadcast to leading_shape.

This is the canonical aggregation an ELBO needs. Objectives that want particle-aware or per-site granularity can skip this helper and aggregate themselves.

Source code in src/quivers/inference/registry.py
@staticmethod
def aggregate_log_abs_det(
    log_abs_dets: dict[str, torch.Tensor],
    leading_shape: tuple[int, ...] = (),
) -> torch.Tensor:
    """Sum every per-site ``log_abs_det`` over its event axes
    and produce a single tensor broadcast to ``leading_shape``.

    This is the canonical aggregation an ELBO needs. Objectives
    that want particle-aware or per-site granularity can skip
    this helper and aggregate themselves.
    """
    if not log_abs_dets:
        return torch.zeros(leading_shape) if leading_shape else torch.zeros(())
    total: torch.Tensor | None = None
    n_leading = len(leading_shape)
    for site_lad in log_abs_dets.values():
        # Sum away every axis beyond the leading shape; what
        # remains is broadcast against the leading shape.
        while site_lad.dim() > n_leading:
            site_lad = site_lad.sum(dim=-1)
        total = site_lad if total is None else total + site_lad
    assert total is not None
    return total

zero_unconstrained

zero_unconstrained(*, leading_shape: tuple[int, ...] = (), device: device | None = None, dtype: dtype | None = None) -> dict[str, Tensor]

Return a dict of zero-initialized unconstrained site tensors with the supplied leading batch shape.

Useful for HMC chain initialisation and AutoLaplace's MAP starting point.

Source code in src/quivers/inference/registry.py
def zero_unconstrained(
    self,
    *,
    leading_shape: tuple[int, ...] = (),
    device: torch.device | None = None,
    dtype: torch.dtype | None = None,
) -> dict[str, torch.Tensor]:
    """Return a dict of zero-initialized unconstrained site
    tensors with the supplied leading batch shape.

    Useful for HMC chain initialisation and AutoLaplace's MAP
    starting point.
    """
    out: dict[str, torch.Tensor] = {}
    for site in self._sites.values():
        shape = leading_shape + site.unconstrained_shape
        out[site.name] = torch.zeros(shape, device=device, dtype=dtype)
    return out

randn_unconstrained

randn_unconstrained(*, leading_shape: tuple[int, ...] = (), device: device | None = None, dtype: dtype | None = None, scale: float = 1.0) -> dict[str, Tensor]

Standard-normal-initialized unconstrained site tensors.

Source code in src/quivers/inference/registry.py
def randn_unconstrained(
    self,
    *,
    leading_shape: tuple[int, ...] = (),
    device: torch.device | None = None,
    dtype: torch.dtype | None = None,
    scale: float = 1.0,
) -> dict[str, torch.Tensor]:
    """Standard-normal-initialized unconstrained site tensors."""
    out: dict[str, torch.Tensor] = {}
    for site in self._sites.values():
        shape = leading_shape + site.unconstrained_shape
        out[site.name] = scale * torch.randn(shape, device=device, dtype=dtype)
    return out

Flow transforms

The learnable bijections that AutoNormalizingFlow and its subclasses stack. A custom flow subclasses TransformModule.

transforms

Bijector and normalizing-flow primitives.

This module collects the differentiable bijections quivers's variational guides chain through. Every primitive is a subclass of torch.distributions.transforms.Transform, so they compose under torch.distributions.transforms.ComposeTransform, plug into torch.distributions.transforms.biject_to-style pipelines, and interop cleanly with torch.distributions.transformed_distribution.TransformedDistribution.

Coverage

  • AffineCouplingTransform: RealNVP coupling layer (Dinh, Sohl-Dickstein, Bengio 2017, doi:10.48550/arXiv.1605.08803 <https://doi.org/10.48550/arXiv.1605.08803>_). Splits the input into two halves, scales / shifts one half conditional on the other.
  • MaskedAutoregressiveTransform: MAF (Papamakarios, Pavlakou, Murray 2017, doi:10.48550/arXiv.1705.07057 <https://doi.org/10.48550/arXiv.1705.07057>_). Forward pass is parallel (single masked MLP call); inverse is sequential (per-coordinate). The mass-density form used by variational inference.
  • InverseAutoregressiveTransform: IAF (Kingma, Salimans, Jozefowicz et al. 2016, doi:10.48550/arXiv.1606.04934 <https://doi.org/10.48550/arXiv.1606.04934>_). The dual of MAF: sampling is parallel, density evaluation is sequential. Preferred when you sample more often than score (which is true for variational guides).
  • NeuralSplineCouplingTransform: monotone rational-quadratic spline coupling (Durkan, Bekasov, Murray, Papamakarios 2019, doi:10.48550/arXiv.1906.04032 <https://doi.org/10.48550/arXiv.1906.04032>_). Allows nonlinear monotone transformations within each coupling layer. Expressiveness depends on the spline and network configuration.
  • LULinearTransform: LU-decomposed linear permutation (Kingma, Dhariwal 2018 Glow, doi:10.48550/arXiv.1807.03039 <https://doi.org/10.48550/arXiv.1807.03039>_). Cheap learnable invertible linear layer; the standard inter- coupling-layer mixer.
  • BatchNormTransform: normalization by running moments as a normalizing-flow transform, after Dinh, Sohl-Dickstein, Bengio (2017, the RealNVP paper); the moments are updated explicitly, so the layer is one bijection between updates.

Every primitive is fully implemented (forward, inverse, log_abs_det_jacobian). No primitive raises NotImplementedError under any input its type signature accepts. The masked-network factories are designed so callers can pass a callable / module rather than configuring topology through string flags.

TransformModule

TransformModule(cache_size: int = 0)

Bases: Transform, Module

Cooperative base for transforms that also need to register torch.nn.Parameter and torch.nn.Module.register_buffer attributes.

torch.distributions.transforms.Transform is not a torch.nn.Module, so subclassing both is required for any flow primitive that holds learnable parameters or buffers (every primitive in this module). The cooperative base calls both __init__\ s in MRO order, nn.Module first so attribute storage is set up before Transform populates the cache-size machinery.

Source code in src/quivers/inference/transforms.py
def __init__(self, cache_size: int = 0) -> None:
    nn.Module.__init__(self)
    Transform.__init__(self, cache_size=cache_size)

update_statistics

update_statistics(inputs: Tensor) -> None

Fold a batch of this layer's inputs into its data-dependent state.

A layer whose map is fixed by statistics of its inputs (a BatchNormTransform) overrides this; the layer's map is the same bijection before and after every call of its forward, inverse, and log-determinant, and changes only here. A layer without such state has nothing to update, which this default states.

PARAMETER DESCRIPTION
inputs

Points of the layer's domain, shape (n, dim).

TYPE: Tensor

Source code in src/quivers/inference/transforms.py
def update_statistics(self, inputs: torch.Tensor) -> None:
    """Fold a batch of this layer's inputs into its data-dependent state.

    A layer whose map is fixed by statistics of its inputs (a
    `BatchNormTransform`) overrides this; the layer's map is the
    same bijection before and after every call of its forward,
    inverse, and log-determinant, and changes only here. A layer
    without such state has nothing to update, which this default
    states.

    Parameters
    ----------
    inputs : torch.Tensor
        Points of the layer's domain, shape ``(n, dim)``.
    """
    del inputs

AffineCouplingTransform

AffineCouplingTransform(dim: int, net: Module, mask: Tensor)

Bases: TransformModule

RealNVP-style affine coupling transform.

Splits the input vector into two parts: an "identity" part x_a and a "transformed" part x_b. The transformed part is shifted and scaled by parameters output from a neural network that sees only the identity part. The Jacobian is triangular, so its log-determinant is the sum of the log-scales on x_b.

PARAMETER DESCRIPTION
dim

Total event dimension.

TYPE: int

net

Module mapping x_a of shape (..., dim_a) to (log_scale_b, shift_b) of shape (..., 2 * dim_b). The factory make_coupling_mlp builds a sensible default.

TYPE: Module

mask

Boolean mask of shape (dim,): True entries form the identity part, False entries form the transformed part. Permuting the mask between consecutive coupling layers is the canonical RealNVP recipe.

TYPE: Tensor

Source code in src/quivers/inference/transforms.py
def __init__(self, dim: int, net: nn.Module, mask: torch.Tensor) -> None:
    TransformModule.__init__(self, cache_size=1)
    if mask.dtype != torch.bool:
        raise TypeError(
            f"AffineCouplingTransform: mask must be bool, got {mask.dtype}"
        )
    if mask.shape != (dim,):
        raise ValueError(
            f"AffineCouplingTransform: mask shape {tuple(mask.shape)} "
            f"does not match dim={dim}"
        )
    n_a = int(mask.sum().item())
    n_b = dim - n_a
    if n_a == 0 or n_b == 0:
        raise ValueError(
            f"AffineCouplingTransform: mask must split the input into "
            f"two non-empty parts; got {n_a} identity / {n_b} transformed"
        )
    self._dim = dim
    self._n_a = n_a
    self._n_b = n_b
    self.net = net
    self.register_buffer("_mask", mask, persistent=True)

MADE

MADE(dim: int, n_per_dim: int, *, hidden: int = 64, n_hidden_layers: int = 2, ordering: Tensor | None = None)

Bases: Module

Masked Autoencoder for Distribution Estimation (Germain, Gregor, Murray, and Larochelle 2015) Germain et al. (2015).

Outputs n_per_dim parameters per input coordinate. The masking guarantees that output parameters for coordinate j depend only on input coordinates < j in the supplied ordering, which is the autoregressive property MAF / IAF exploit.

Source code in src/quivers/inference/transforms.py
def __init__(
    self,
    dim: int,
    n_per_dim: int,
    *,
    hidden: int = 64,
    n_hidden_layers: int = 2,
    ordering: torch.Tensor | None = None,
) -> None:
    super().__init__()
    if ordering is None:
        ordering = torch.arange(dim)
    if ordering.shape != (dim,) or ordering.dtype != torch.long:
        raise TypeError("MADE: ordering must be a long tensor of shape (dim,)")
    self._dim = dim
    self._n_per_dim = n_per_dim
    self.register_buffer("_ordering", ordering, persistent=True)
    # Assign integer "degrees" to each hidden unit so that the
    # masking enforces autoregressivity.
    hidden_degrees = [
        torch.randint(1, dim, (hidden,)) for _ in range(n_hidden_layers)
    ]
    # Input degrees: ordering itself; output degrees: ordering
    # repeated n_per_dim times (one block per output parameter).
    in_degrees = ordering
    layers: list[nn.Module] = []
    prev_degrees = in_degrees
    prev_size = dim
    for h_degrees in hidden_degrees:
        mask = (h_degrees.unsqueeze(1) >= prev_degrees.unsqueeze(0)).to(
            torch.float32
        )
        layers.append(_MaskedLinear(prev_size, hidden, mask))
        layers.append(nn.ReLU())
        prev_degrees = h_degrees
        prev_size = hidden
    # Final layer: strict-less-than for the autoregressive
    # property; one output block per parameter.
    out_degrees = ordering.repeat(n_per_dim)
    final_mask = (out_degrees.unsqueeze(1) > prev_degrees.unsqueeze(0)).to(
        torch.float32
    )
    final = _MaskedLinear(prev_size, dim * n_per_dim, final_mask)
    nn.init.zeros_(final.weight)
    nn.init.zeros_(final.bias)
    layers.append(final)
    self.net = nn.Sequential(*layers)

MaskedAutoregressiveTransform

MaskedAutoregressiveTransform(made: MADE)

Bases: TransformModule

Masked Autoregressive Flow (MAF) layer.

Forward (density) is parallel, one MADE call. Inverse (sampling) is sequential in the autoregressive order.

PARAMETER DESCRIPTION
made

Masked network producing per-coordinate (shift, log_scale).

TYPE: MADE

Source code in src/quivers/inference/transforms.py
def __init__(self, made: MADE) -> None:
    super().__init__(cache_size=1)
    if made.n_per_dim != 2:
        raise ValueError(
            f"MaskedAutoregressiveTransform: MADE must have "
            f"n_per_dim == 2 (shift, log_scale), got {made.n_per_dim}"
        )
    self.made = made

InverseAutoregressiveTransform

InverseAutoregressiveTransform(made: MADE)

Bases: TransformModule

Inverse Autoregressive Flow (IAF) layer.

Dual of MaskedAutoregressiveTransform: sampling (forward) is parallel, density (inverse) is sequential. The preferred direction for variational guides because we sample more often than we score.

PARAMETER DESCRIPTION
made

Masked network producing per-coordinate (shift, log_scale).

TYPE: MADE

Source code in src/quivers/inference/transforms.py
def __init__(self, made: MADE) -> None:
    super().__init__(cache_size=1)
    if made.n_per_dim != 2:
        raise ValueError(
            f"InverseAutoregressiveTransform: MADE must have "
            f"n_per_dim == 2 (shift, log_scale), got {made.n_per_dim}"
        )
    self.made = made

NeuralSplineCouplingTransform

NeuralSplineCouplingTransform(dim: int, net: Module, mask: Tensor, *, num_bins: int = 8, tail_bound: float = 3.0)

Bases: TransformModule

Monotone rational-quadratic spline coupling (Durkan-Bekasov-Murray-Papamakarios 2019).

Same coupling structure as AffineCouplingTransform, but the per-coordinate transform on x_b is a monotone rational-quadratic spline rather than an affine map. The network outputs (unnormalized_widths, unnormalized_heights, unnormalized_derivatives) per transformed coordinate; num_bins knots per coordinate.

PARAMETER DESCRIPTION
dim

Event dimension.

TYPE: int

net

Maps x_a of shape (..., n_a) to spline parameters of shape (..., n_b * (3 * num_bins - 1)). make_coupling_mlp produces a sensible default with n_out = n_b * (3 * num_bins - 1).

TYPE: Module

mask

Boolean mask of shape (dim,).

TYPE: Tensor

num_bins

Number of spline knots.

TYPE: int DEFAULT: 8

tail_bound

Domain of the spline; outside [-tail_bound, tail_bound] the transform is the identity.

TYPE: float DEFAULT: 3.0

Source code in src/quivers/inference/transforms.py
def __init__(
    self,
    dim: int,
    net: nn.Module,
    mask: torch.Tensor,
    *,
    num_bins: int = 8,
    tail_bound: float = 3.0,
) -> None:
    super().__init__(cache_size=1)
    if mask.dtype != torch.bool or mask.shape != (dim,):
        raise ValueError(
            "NeuralSplineCouplingTransform: mask must be bool of shape "
            f"(dim,) = ({dim},); got {tuple(mask.shape)} {mask.dtype}"
        )
    n_a = int(mask.sum().item())
    n_b = dim - n_a
    if n_a == 0 or n_b == 0:
        raise ValueError(
            "NeuralSplineCouplingTransform: mask must split the input "
            f"into two non-empty parts; got {n_a} / {n_b}"
        )
    self._dim = dim
    self._n_a = n_a
    self._n_b = n_b
    self._num_bins = num_bins
    self._tail_bound = tail_bound
    self.net = net
    self.register_buffer("_mask", mask, persistent=True)

LULinearTransform

LULinearTransform(dim: int, perm: Tensor | None = None)

Bases: TransformModule

Invertible linear layer parameterized as :math:A = P L U (Kingma & Dhariwal 2018 Glow).

The unit-lower-triangular L and unit-upper-triangular U factors are stored along with their respective off-diagonal weights; the diagonal of U is stored as a log-scale so the layer remains invertible and the log-determinant is the sum of the log-scales. P is a fixed permutation chosen at construction.

Source code in src/quivers/inference/transforms.py
def __init__(self, dim: int, perm: torch.Tensor | None = None) -> None:
    super().__init__(cache_size=1)
    self._dim = dim
    # Lower-triangular off-diagonal (strict)
    self._lower = nn.Parameter(torch.zeros(dim, dim))
    # Upper-triangular off-diagonal (strict)
    self._upper = nn.Parameter(torch.zeros(dim, dim))
    # Log-magnitude of U's diagonal; sign baked into the
    # signed-zero init below so the layer starts as identity.
    self._log_diag = nn.Parameter(torch.zeros(dim))
    if perm is None:
        perm = torch.arange(dim)
    if perm.shape != (dim,):
        raise ValueError(
            f"LULinearTransform: perm shape {tuple(perm.shape)} != ({dim},)"
        )
    self.register_buffer("_perm", perm.long(), persistent=True)
    # The fixed permutation matrix's log-det is 0 (it's a
    # signed permutation; we take +1 here).
    self.register_buffer(
        "_lower_mask",
        torch.tril(torch.ones(dim, dim), diagonal=-1),
        persistent=True,
    )
    self.register_buffer(
        "_upper_mask",
        torch.triu(torch.ones(dim, dim), diagonal=1),
        persistent=True,
    )
    self.register_buffer("_eye", torch.eye(dim), persistent=True)

BatchNormTransform

BatchNormTransform(dim: int, *, momentum: float = 0.1, eps: float = 1e-05)

Bases: TransformModule

Normalization by running moments as a normalizing-flow layer.

The layer is the coordinatewise affine bijection

.. math::

T(x) = \frac{x - m}{\sqrt{v + \epsilon}}\, e^{\gamma} + \beta,
\qquad
\log|\det J_T(x)| = \sum_i \bigl(\gamma_i
    - \tfrac12 \log(v_i + \epsilon)\bigr),

with learned :math:\gamma, \beta and the running moments :math:m, v (buffers). Forward, inverse, and log-determinant use the same :math:m, v, so they are one bijection, and each row of a (..., dim) input is mapped alone: a flow guide built on the layer has a density for each run that does not depend on the other runs.

The normalization of Dinh, Sohl-Dickstein, and Bengio (2017), Density estimation using Real NVP, uses the moments of the current minibatch in training. That map changes with the minibatch, so its "density" of one point depends on the other points scored with it and is not the density of any law over one run; an objective built from it is not the objective of a guide. The layer does not compute it, and torch.nn.Module.train does not change the map. The moments are instead data-dependent state, folded in by update_statistics from a batch of the layer's inputs, between objective evaluations (AutoNormalizingFlow.update_statistics does this for every layer of a flow guide). Each evaluation is then the objective of the guide at the current moments, and an update moves the guide as a parameter update outside the gradient does.

PARAMETER DESCRIPTION
dim

Number of coordinates.

TYPE: int

momentum

Weight of a new batch's moments in the running moments, in (0, 1].

TYPE: float DEFAULT: 0.1

eps

The constant :math:\epsilon added to the variance.

TYPE: float DEFAULT: 1e-05

RAISES DESCRIPTION
ValueError

If momentum is outside (0, 1] or eps is not positive.

Source code in src/quivers/inference/transforms.py
def __init__(
    self,
    dim: int,
    *,
    momentum: float = 0.1,
    eps: float = 1e-5,
) -> None:
    if not 0.0 < momentum <= 1.0:
        raise ValueError(
            f"BatchNormTransform: momentum must be in (0, 1], got {momentum}"
        )
    if not eps > 0.0:
        raise ValueError(f"BatchNormTransform: eps must be positive, got {eps}")
    super().__init__(cache_size=0)
    self._dim = dim
    self._momentum = momentum
    self._eps = eps
    self._gamma = nn.Parameter(torch.zeros(dim))  # log-scale
    self._beta = nn.Parameter(torch.zeros(dim))
    self.register_buffer("_running_mean", torch.zeros(dim), persistent=True)
    self.register_buffer("_running_var", torch.ones(dim), persistent=True)

update_statistics

update_statistics(inputs: Tensor) -> None

Fold the moments of a batch of inputs into the running moments.

:math:m \leftarrow (1 - \mu) m + \mu \bar x and :math:v \leftarrow (1 - \mu) v + \mu s^2, with :math:\bar x and :math:s^2 the mean and the (biased) variance of the batch per coordinate and :math:\mu the momentum, outside the gradient.

PARAMETER DESCRIPTION
inputs

Points of the layer's domain, shape (n, dim) with n >= 2.

TYPE: Tensor

RAISES DESCRIPTION
ValueError

If inputs is not (n, dim) with at least two rows.

Source code in src/quivers/inference/transforms.py
def update_statistics(self, inputs: torch.Tensor) -> None:
    """Fold the moments of a batch of inputs into the running moments.

    :math:`m \\leftarrow (1 - \\mu) m + \\mu \\bar x` and
    :math:`v \\leftarrow (1 - \\mu) v + \\mu s^2`, with
    :math:`\\bar x` and :math:`s^2` the mean and the (biased)
    variance of the batch per coordinate and :math:`\\mu` the
    momentum, outside the gradient.

    Parameters
    ----------
    inputs : torch.Tensor
        Points of the layer's domain, shape ``(n, dim)`` with
        ``n >= 2``.

    Raises
    ------
    ValueError
        If ``inputs`` is not ``(n, dim)`` with at least two rows.
    """
    if inputs.dim() != 2 or inputs.shape[1] != self._dim or inputs.shape[0] < 2:
        raise ValueError(
            f"BatchNormTransform.update_statistics: inputs must have shape "
            f"(n, {self._dim}) with n >= 2, got {tuple(inputs.shape)}"
        )
    mean, var = self._moments()
    with torch.no_grad():
        batch = inputs.detach().to(mean)
        mean.mul_(1 - self._momentum).add_(batch.mean(dim=0) * self._momentum)
        var.mul_(1 - self._momentum).add_(
            batch.var(dim=0, unbiased=False) * self._momentum
        )

make_coupling_mlp

make_coupling_mlp(n_in: int, n_out: int, *, hidden: int = 64, n_hidden_layers: int = 2, activation: type[Module] = ReLU) -> Module

Build an MLP for use as the net argument of AffineCouplingTransform or NeuralSplineCouplingTransform.

The output layer is initialized to zero so the transform starts as the identity, which is a standard normalizing-flow initialisation (see Glow, Real NVP).

Source code in src/quivers/inference/transforms.py
def make_coupling_mlp(
    n_in: int,
    n_out: int,
    *,
    hidden: int = 64,
    n_hidden_layers: int = 2,
    activation: type[nn.Module] = nn.ReLU,
) -> nn.Module:
    """Build an MLP for use as the ``net`` argument of
    `AffineCouplingTransform` or
    `NeuralSplineCouplingTransform`.

    The output layer is initialized to zero so the transform
    starts as the identity, which is a standard normalizing-flow
    initialisation (see Glow, Real NVP).
    """
    layers: list[nn.Module] = [nn.Linear(n_in, hidden), activation()]
    for _ in range(n_hidden_layers - 1):
        layers.append(nn.Linear(hidden, hidden))
        layers.append(activation())
    final = nn.Linear(hidden, n_out)
    nn.init.zeros_(final.weight)
    nn.init.zeros_(final.bias)
    layers.append(final)
    return nn.Sequential(*layers)

alternating_mask

alternating_mask(dim: int, *, even: bool = True) -> Tensor

Boolean mask alternating True / False. Even-indexed entries are True when even=True.

Source code in src/quivers/inference/transforms.py
def alternating_mask(dim: int, *, even: bool = True) -> torch.Tensor:
    """Boolean mask alternating ``True`` / ``False``. Even-indexed
    entries are ``True`` when ``even=True``."""
    indices = torch.arange(dim)
    return (indices % 2 == 0) if even else (indices % 2 == 1)

half_mask

half_mask(dim: int, *, first_half_true: bool = True) -> Tensor

Boolean mask with the first / second half True.

Source code in src/quivers/inference/transforms.py
def half_mask(dim: int, *, first_half_true: bool = True) -> torch.Tensor:
    """Boolean mask with the first / second half ``True``."""
    mask = torch.zeros(dim, dtype=torch.bool)
    half = dim // 2
    if first_half_true:
        mask[:half] = True
    else:
        mask[half:] = True
    return mask

Annealed importance sampling

dais

Differentiable annealed importance sampling (DAIS) guide.

DAIS runs a short chain of uncorrected Hamiltonian transitions from a base guide :math:q_0 toward the posterior and uses the chain's endpoint as the variational draw (Zhang, Hsu, Li, Finn and Grosse 2021; Geffner and Domke 2021). Transition :math:k draws a fresh momentum :math:v_{k-1} \sim \mathcal{N}(0, I) and applies leapfrog steps on the bridge :math:\pi_k \propto q_0^{1-\beta_k} p^{\beta_k}, ending at :math:(u_k, \hat v_k); there is no Metropolis correction. The step sizes, the inverse-temperature schedule :math:\beta_k, and the base guide's parameters are all variational parameters, and the whole trajectory is differentiated through, including the bridge gradients inside each leapfrog step.

Leapfrog is volume preserving, so the forward chain over :math:(u_0, v_0, \dots, v_{K-1}) and its time reversal define the extended-space importance weight (Zhang et al. 2021, Eq. 15)

.. math::

\log w = \log p(u_K, y) - \log q_0(u_0)
    + \sum_{k=1}^{K} \bigl[\log \mathcal{N}(\hat v_k)
                          - \log \mathcal{N}(v_{k-1})\bigr],

with densities taken in the unconstrained space where the chain runs (each including its bijector's log-Jacobian). Its expectation under the forward chain is :math:\mathbb{E}[w] = p(y), so :math:\mathbb{E}[\log w] \le \log p(y) is a valid lower bound and the multi-sample objectives built from w are valid bounds as well. The bridges and step sizes shape the chain, not the validity of the bound; an uncorrected chain does not leave the bridges invariant, so the AIS weight :math:\sum_k (\beta_k - \beta_{k-1}) (\log p - \log q_0) evaluated along it would not be a valid bound and is not used. The bound is not guaranteed to improve on the base guide's ELBO, and a fitted run need not recover every posterior mode.

AutoDAIS.rsample_strata returns the endpoint together with its extended-space log-density :math:\log q_0(u_0) - \log|J(u_K)| + \sum_k [K(\hat v_k) - K(v_{k-1})] (:math:K the kinetic energy), so that log p - log q for the draw is exactly :math:\log w. The endpoint has no closed-form marginal density, so AutoDAIS.log_prob raises: the estimators and objectives that need the guide density at a fixed point (StickingTheLanding, DoublyReparameterized, ScoreFunction, RWS) are not available with this guide; use the reparameterized estimator.

References: Zhang, Hsu, Li, Finn and Grosse (2021), Differentiable Annealed Importance Sampling and the Perils of Gradient Noise; Geffner and Domke (2021), MCMC Variational Inference via Uncorrected Hamiltonian Annealing.

AutoDAIS

AutoDAIS(base: Guide, model: MonadicProgram, observations: dict[str, Tensor], x: Tensor | None = None, num_steps: int = 8, leapfrog_steps: int = 1, init_step_size: float = 0.1, init_temperature: float = 0.1)

Bases: Guide

Annealed-importance-sampling guide wrapping a base guide.

PARAMETER DESCRIPTION
base

Base variational guide (the chain's start). Must be built against the same model + observed-name set the DAIS guide is for, and must have a density at arbitrary points. AutoNormalGuide or AutoMultivariateNormalGuide are the canonical choices.

TYPE: Guide

model

Generative model. Required because the bridges need the target log-density.

TYPE: MonadicProgram

observations

Observed-site values that pin the model's likelihood in the bridges. They shape the dynamics only: the bound that an objective evaluates uses that objective's own input and observations, and is valid for any of them, though the chain is tuned for these.

TYPE: dict[str, Tensor]

x

Program input fed to the model's log-joint inside the bridges: one row, since the bridges target one run's posterior. Default torch.zeros(1, 1).

TYPE: Tensor DEFAULT: None

num_steps

Number of Hamiltonian transitions along the path; at least 1. Default 8.

TYPE: int DEFAULT: 8

leapfrog_steps

Leapfrog substeps per transition. Default 1.

TYPE: int DEFAULT: 1

init_step_size

Initial leapfrog step size, one learnable value per transition.

TYPE: float DEFAULT: 0.1

init_temperature

Initial first inverse temperature, in (0, 1). The schedule anneals from this value at the first transition to 1.0 at the last and is learnable.

TYPE: float DEFAULT: 0.1

RAISES DESCRIPTION
ValueError

If num_steps < 1, leapfrog_steps < 1, init_step_size <= 0, init_temperature is outside (0, 1), the base registry has no continuous latents, or x has more than one row.

Source code in src/quivers/inference/dais.py
def __init__(
    self,
    base: Guide,
    model: MonadicProgram,
    observations: dict[str, torch.Tensor],
    x: torch.Tensor | None = None,
    num_steps: int = 8,
    leapfrog_steps: int = 1,
    init_step_size: float = 0.1,
    init_temperature: float = 0.1,
) -> None:
    super().__init__()
    if num_steps < 1:
        raise ValueError(f"AutoDAIS: num_steps must be >= 1, got {num_steps}")
    if leapfrog_steps < 1:
        raise ValueError(
            f"AutoDAIS: leapfrog_steps must be >= 1, got {leapfrog_steps}"
        )
    if init_step_size <= 0:
        raise ValueError(
            f"AutoDAIS: init_step_size must be > 0, got {init_step_size}"
        )
    if not 0.0 < init_temperature < 1.0:
        raise ValueError(
            f"AutoDAIS: init_temperature must be in (0, 1), got {init_temperature}"
        )
    self.base = base
    self._registry = base.registry
    self._model = model
    self._observations = observations
    self._x = x if x is not None else torch.zeros(1, 1)
    _require_one_run(self._x, "AutoDAIS")
    # The model's log joint prepared per layout of the bridge's values.
    self._plans = JointPlans(model, self._x)
    self._num_steps = num_steps
    self._leapfrog_steps = leapfrog_steps
    self._D = self._registry.total_unconstrained_dim
    if self._D == 0:
        raise ValueError(
            "AutoDAIS: base registry has zero total "
            "unconstrained dimension; no continuous latents "
            "to anneal over"
        )
    # Learnable trajectory params.
    log_step = torch.log(torch.tensor(float(init_step_size)))
    self.log_step_size = nn.Parameter(log_step.expand(num_steps).clone())
    # Inverse temperatures are the normalized cumulative sum of
    # softplus increments, so they increase monotonically and the
    # last transition anneals at beta = 1 (the full target).
    # Initial schedule: linear in inverse temperature.
    init_betas = torch.linspace(init_temperature, 1.0, num_steps + 1)[:-1]
    increments = torch.zeros(num_steps)
    increments[0] = init_betas[0]
    for i in range(1, num_steps):
        increments[i] = init_betas[i] - init_betas[i - 1]
    # Store log(increments) so cumsum of softplus(raw) is positive
    # and monotone.
    raw_increments = torch.log(torch.expm1(increments.clamp(min=1e-4)))
    self.beta_increments_raw = nn.Parameter(raw_increments)

latent_names property

latent_names: list[str]

Names of the latent sites the guide covers.

RETURNS DESCRIPTION
list[str]

The registry's site names, in order.

observe

observe(observations: Mapping[str, Tensor]) -> None

Forward the step's data to the base guide.

PARAMETER DESCRIPTION
observations

Observed values and host data.

TYPE: Mapping[str, Tensor]

Source code in src/quivers/inference/dais.py
def observe(self, observations: Mapping[str, torch.Tensor]) -> None:
    """Forward the step's data to the base guide.

    Parameters
    ----------
    observations : Mapping[str, torch.Tensor]
        Observed values and host data.
    """
    self.base.observe(observations)

rsample

rsample(x: Tensor) -> dict[str, Tensor]

Endpoint of one annealed trajectory, as trace-side values.

One trajectory is run per call and shared by every row of x's batch axis. The endpoint has no closed-form density, so objectives draw through rsample_strata, which returns the trajectory's density with the draw.

PARAMETER DESCRIPTION
x

Program input, shape (batch, ...).

TYPE: Tensor

RETURNS DESCRIPTION
dict[str, Tensor]

Non-plate sites at (batch, *constrained_shape) and plate sites at constrained_shape.

Source code in src/quivers/inference/dais.py
def rsample(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
    """Endpoint of one annealed trajectory, as trace-side values.

    One trajectory is run per call and shared by every row of
    ``x``'s batch axis. The endpoint has no closed-form density, so
    objectives draw through `rsample_strata`, which returns the
    trajectory's density with the draw.

    Parameters
    ----------
    x : torch.Tensor
        Program input, shape ``(batch, ...)``.

    Returns
    -------
    dict[str, torch.Tensor]
        Non-plate sites at ``(batch, *constrained_shape)`` and
        plate sites at ``constrained_shape``.
    """
    z_final, _ = self._trajectory(x)
    return self._materialise_constrained(z_final, int(x.shape[0]))

rsample_strata

rsample_strata(x: Tensor) -> tuple[GuideDraw, ...]

One trajectory's endpoint with its extended-space density.

The draw's log_density is the extended-space log-density of the trajectory that produced it, so for a model and input whose log-joint at the endpoint is :math:\log p(z_K, y), the value log p - log_density is the trajectory's DAIS log-weight :math:\log w, and ELBO estimates :math:\mathbb{E}[\log w] \le \log p(y). Each call runs a fresh trajectory, so several particles are independent.

PARAMETER DESCRIPTION
x

Program input, shape (batch, ...).

TYPE: Tensor

RETURNS DESCRIPTION
tuple[GuideDraw, ...]

A single draw with log-weight zero; its density is expanded to (batch,).

Source code in src/quivers/inference/dais.py
def rsample_strata(self, x: torch.Tensor) -> tuple[GuideDraw, ...]:
    """One trajectory's endpoint with its extended-space density.

    The draw's ``log_density`` is the extended-space log-density of
    the trajectory that produced it, so for a model and input whose
    log-joint at the endpoint is :math:`\\log p(z_K, y)`, the value
    ``log p - log_density`` is the trajectory's DAIS log-weight
    :math:`\\log w`, and ``ELBO`` estimates
    :math:`\\mathbb{E}[\\log w] \\le \\log p(y)`. Each call runs a
    fresh trajectory, so several particles are independent.

    Parameters
    ----------
    x : torch.Tensor
        Program input, shape ``(batch, ...)``.

    Returns
    -------
    tuple[GuideDraw, ...]
        A single draw with log-weight zero; its density is
        expanded to ``(batch,)``.
    """
    z_final, log_density = self._trajectory(x)
    batch = int(x.shape[0])
    return (
        GuideDraw(
            sites=self._materialise_constrained(z_final, batch),
            log_density=log_density.expand(batch),
            log_weight=torch.zeros((), device=x.device, dtype=log_density.dtype),
        ),
    )

log_prob

log_prob(x: Tensor, sites: dict[str, Tensor]) -> Tensor

Refuse: the DAIS endpoint has no density at arbitrary sites.

The endpoint's marginal density integrates over every momentum draw of the trajectory and has no closed form. Its extended-space density is defined only for the trajectory that produced a draw and is returned with the draw by rsample_strata, which the objectives use.

PARAMETER DESCRIPTION
x

Program input.

TYPE: Tensor

sites

Site values to score.

TYPE: dict[str, Tensor]

RETURNS DESCRIPTION
Tensor

Never returns.

RAISES DESCRIPTION
ValueError

Always.

Source code in src/quivers/inference/dais.py
def log_prob(
    self,
    x: torch.Tensor,
    sites: dict[str, torch.Tensor],
) -> torch.Tensor:
    """Refuse: the DAIS endpoint has no density at arbitrary sites.

    The endpoint's marginal density integrates over every momentum
    draw of the trajectory and has no closed form. Its
    extended-space density is defined only for the trajectory that
    produced a draw and is returned with the draw by
    `rsample_strata`, which the objectives use.

    Parameters
    ----------
    x : torch.Tensor
        Program input.
    sites : dict[str, torch.Tensor]
        Site values to score.

    Returns
    -------
    torch.Tensor
        Never returns.

    Raises
    ------
    ValueError
        Always.
    """
    del x, sites
    raise ValueError(
        "AutoDAIS has no density at arbitrary sites: the endpoint's "
        "density is defined only on the extended space of the trajectory "
        "that produced it, which rsample_strata returns with the draw. "
        "Objectives that need the guide density at a fixed point "
        "(StickingTheLanding, DoublyReparameterized, ScoreFunction, RWS) "
        "are not available with AutoDAIS; use "
        "estimator=Reparameterized()."
    )

Cited sources

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).

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.

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 J. C. MacKay. Information Theory, Inference, and Learning Algorithms. Cambridge University Press, 2003. ISBN 9780521642989. URL: https://assets.cambridge.org/97805216/42989/frontmatter/9780521642989_frontmatter.pdf.

Luke Tierney and Joseph B. Kadane. Accurate Approximations for Posterior Moments and Marginal Densities. Journal of the American Statistical Association, 81(393):82–86, 1986. URL: https://www.tandfonline.com/doi/abs/10.1080/01621459.1986.10478240, doi:10.1080/01621459.1986.10478240.

Mathieu Germain, Karol Gregor, Iain Murray, and Hugo Larochelle. MADE: Masked Autoencoder for Distribution Estimation. In Proceedings of the 32nd International Conference on Machine Learning, volume 37 of Proceedings of Machine Learning Research, 881–889. 2015. URL: https://proceedings.mlr.press/v37/germain15.html.

Diederik P. Kingma and Prafulla Dhariwal. Glow: Generative Flow with Invertible 1x1 Convolutions. In Advances in Neural Information Processing Systems, volume 31. 2018. URL: https://proceedings.neurips.cc/paper/2018/hash/d139db6a236200b21cc7f752979132d0-Abstract.html.