Skip to content

Tensor Distribution Backend

TensorBackend samples and scores the runtime distributions of the reference machine by torch. It builds each family's distribution as the compiled runtime builds the value of a Distribution term, so the two score a family by the same code, and every density keeps its gradient.

tensor_backend

The reference machine's distributions, sampled and scored by torch.

A quivers.qiec.distributions.RuntimeDistribution names a family, its arguments as tensors, and the plate it is drawn over. TensorBackend builds the family's torch distribution exactly as the compiled runtime builds the value of a Distribution term, with the plate's axes as the distribution's leading batch axes, so the machine and the compiled runtime score a family by the same code. A density keeps the gradient of every argument and of the point, and a draw of a reparameterizable family keeps the gradient of the arguments; a draw of any other family is a sample whose law depends on the arguments, which no derivative of the draw itself accounts for, and has none.

TorchArgument

TorchArgument = Tensor | Distribution | tuple[TorchArgument, ...]

An argument of a torch family: a tensor, a distribution, or a tuple.

TensorBackend

Sampling and scoring by torch, with gradients.

Every density is the family's torch log_prob at once over the plate, with the plate's event axes summed; draws use torch's global generator.

differentiable property

differentiable: bool

Yes: densities and reparameterized draws keep their gradients.

RETURNS DESCRIPTION
bool

True.

sample

sample(distribution: RuntimeDistribution, rng: Random) -> object

Draw at every position of the plate.

In a pass over many runs at once (quivers._positions.map_positions) every run draws its own value: the draw is made beneath the mapping by quivers._positions.draw, over a distribution whose arguments lead with the run axis.

PARAMETER DESCRIPTION
distribution

The distribution.

TYPE: RuntimeDistribution

rng

Unused: torch draws from its own generator.

TYPE: Random

RETURNS DESCRIPTION
object

The draw, reparameterized when the family allows it.

RAISES DESCRIPTION
DistributionError

If the family has no torch distribution for its arguments.

Source code in src/quivers/continuous/tensor_backend.py
def sample(self, distribution: RuntimeDistribution, rng: random.Random) -> object:
    """Draw at every position of the plate.

    In a pass over many runs at once (`quivers._positions.map_positions`)
    every run draws its own value: the draw is made beneath the mapping
    by `quivers._positions.draw`, over a distribution whose arguments
    lead with the run axis.

    Parameters
    ----------
    distribution : RuntimeDistribution
        The distribution.
    rng : random.Random
        Unused: torch draws from its own generator.

    Returns
    -------
    object
        The draw, reparameterized when the family allows it.

    Raises
    ------
    DistributionError
        If the family has no torch distribution for its arguments.
    """
    del rng
    kind = number_kind(family_record(distribution.family).element)
    tensors: list[torch.Tensor] = []
    expanded = _expanded(distribution, tensors)

    def drawing(
        values: tuple[torch.Tensor, ...], count: int | None
    ) -> torch.Tensor:
        """Draw from the distribution over the given tensors.

        Parameters
        ----------
        values : tuple[torch.Tensor, ...]
            Its tensors, in the order they were collected; each leads
            with the run axis when ``count`` is a number.
        count : int | None
            The number of runs drawn at once, or ``None``.

        Returns
        -------
        torch.Tensor
            The draw, leading with the run axis when there is one.
        """
        native = torch_law(_rebuilt(expanded, iter(values), count))
        drawn = native.rsample() if native.has_rsample else native.sample()
        return _draw(drawn, kind, distribution.numbers)

    return _positions.draw(drawing, tuple(tensors))

log_prob

log_prob(distribution: RuntimeDistribution, value: object, keep_batch: bool) -> Tensor

Evaluate the log density at a point.

PARAMETER DESCRIPTION
distribution

The distribution.

TYPE: RuntimeDistribution

value

The point.

TYPE: object

keep_batch

Whether to keep one density per batch position.

TYPE: bool

RETURNS DESCRIPTION
Tensor

The density in the run's real dtype, its plate event axes summed, its batch axes summed unless kept.

RAISES DESCRIPTION
DistributionError

If the family has no torch distribution for its arguments, or the point is not shaped like the plate.

Source code in src/quivers/continuous/tensor_backend.py
def log_prob(
    self, distribution: RuntimeDistribution, value: object, keep_batch: bool
) -> torch.Tensor:
    """Evaluate the log density at a point.

    Parameters
    ----------
    distribution : RuntimeDistribution
        The distribution.
    value : object
        The point.
    keep_batch : bool
        Whether to keep one density per batch position.

    Returns
    -------
    torch.Tensor
        The density in the run's real dtype, its plate event axes
        summed, its batch axes summed unless kept.

    Raises
    ------
    DistributionError
        If the family has no torch distribution for its arguments, or
        the point is not shaped like the plate.
    """
    native = torch_law(distribution)
    density = native.log_prob(_point(value, native))
    kept = len(distribution.batch) if keep_batch else 0
    if density.dim() < kept:
        raise DistributionError(
            f"a point of {distribution.family} scored under a plate of "
            f"{kept} batch axes has density shape {tuple(density.shape)}"
        )
    if density.dim() > kept:
        density = density.sum(dim=tuple(range(kept, density.dim())))
    return density.to(distribution.numbers.real_dtype)

log_mass

log_mass(distribution: RuntimeDistribution, batch_axes: int) -> Tensor

The log total mass of a construction.

PARAMETER DESCRIPTION
distribution

The distribution.

TYPE: RuntimeDistribution

batch_axes

The leading batch axes kept.

TYPE: int

RETURNS DESCRIPTION
Tensor

The log mass in the run's real dtype.

RAISES DESCRIPTION
DistributionError

If the family has no torch distribution for its arguments.

Source code in src/quivers/continuous/tensor_backend.py
def log_mass(
    self, distribution: RuntimeDistribution, batch_axes: int
) -> torch.Tensor:
    """The log total mass of a construction.

    Parameters
    ----------
    distribution : RuntimeDistribution
        The distribution.
    batch_axes : int
        The leading batch axes kept.

    Returns
    -------
    torch.Tensor
        The log mass in the run's real dtype.

    Raises
    ------
    DistributionError
        If the family has no torch distribution for its arguments.
    """
    mass = measure_log_mass(torch_law(distribution), batch_axes=batch_axes)
    return torch.as_tensor(mass).to(distribution.numbers.real_dtype)

DrawnLaw

DrawnLaw(distribution: RuntimeDistribution, native: Distribution)

Bases: ContinuousMorphism

The law a site of a checked program was drawn from, as a morphism.

A site of a program that runs on the reference machine draws from a RuntimeDistribution its run constructs. A trace records the site's law as the morphism its run drew from, so a latent registry reads its support and event shape, and a guide its bijector, as for a site of a compiled program. The morphism has no input: its law is the one the run constructed, and sampling and scoring it repeat that law.

PARAMETER DESCRIPTION
distribution

The distribution the site was drawn from, at one position of its plate.

TYPE: RuntimeDistribution

native

Its torch distribution.

TYPE: Distribution

Source code in src/quivers/continuous/tensor_backend.py
def __init__(self, distribution: RuntimeDistribution, native: Distribution) -> None:
    natural = tuple(int(size) for size in native.event_shape)
    codomain = Euclidean(
        name=distribution.family,
        dim=math.prod(natural),
        intrinsic_shape=natural,
    )
    super().__init__(Unit, codomain)
    self._native = native
    self._family = distribution.family

family_name property

family_name: str

The family's source name.

RETURNS DESCRIPTION
str

The name.

support property

support: Constraint

The support of the law.

RETURNS DESCRIPTION
Constraint

The torch distribution's support.

rsample

rsample(x: Tensor, sample_shape: Size = Size()) -> Tensor

Draw from the law.

PARAMETER DESCRIPTION
x

Unused: the law has no input.

TYPE: Tensor

sample_shape

Leading sample dimensions.

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

Reparameterized draws when the family allows them.

Source code in src/quivers/continuous/tensor_backend.py
def rsample(  # type: ignore[override]
    self, x: torch.Tensor, sample_shape: torch.Size = torch.Size()
) -> torch.Tensor:
    """Draw from the law.

    Parameters
    ----------
    x : torch.Tensor
        Unused: the law has no input.
    sample_shape : torch.Size
        Leading sample dimensions.

    Returns
    -------
    torch.Tensor
        Reparameterized draws when the family allows them.
    """
    del x
    if self._native.has_rsample:
        return self._native.rsample(sample_shape)
    return self._native.sample(sample_shape)

log_prob

log_prob(x: Tensor, y: Tensor) -> Tensor

The log density of a value.

PARAMETER DESCRIPTION
x

Unused: the law has no input.

TYPE: Tensor

y

The value.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The density at each position of the law's batch.

Source code in src/quivers/continuous/tensor_backend.py
def log_prob(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
    """The log density of a value.

    Parameters
    ----------
    x : torch.Tensor
        Unused: the law has no input.
    y : torch.Tensor
        The value.

    Returns
    -------
    torch.Tensor
        The density at each position of the law's batch.
    """
    del x
    return self._native.log_prob(_point(y, self._native))

torch_law

torch_law(distribution: RuntimeDistribution) -> Distribution

The torch distribution of a runtime distribution.

PARAMETER DESCRIPTION
distribution

The distribution.

TYPE: RuntimeDistribution

RETURNS DESCRIPTION
Distribution

The family's distribution, its batch axes the plate's batch and event axes, its event axes the family's own.

RAISES DESCRIPTION
DistributionError

If the family has no torch constructor for its arguments.

Source code in src/quivers/continuous/tensor_backend.py
def torch_law(distribution: RuntimeDistribution) -> Distribution:
    """The torch distribution of a runtime distribution.

    Parameters
    ----------
    distribution : RuntimeDistribution
        The distribution.

    Returns
    -------
    torch.distributions.Distribution
        The family's distribution, its batch axes the plate's batch and
        event axes, its event axes the family's own.

    Raises
    ------
    DistributionError
        If the family has no torch constructor for its arguments.
    """
    arguments: dict[str, object] = {
        name: _argument(value, distribution.ranks.get(name, 0), distribution.natural)
        for name, value in distribution.arguments.items()
    }
    if distribution.family in SHAPE_FROM_EVENT and distribution.natural:
        arguments["dimension"] = distribution.natural[-1]
    try:
        return _raw_distribution_value(
            distribution.family,
            arguments,
            distribution.natural,
            (*distribution.batch, *distribution.event),
        )
    except (TypeError, ValueError) as error:
        raise DistributionError(
            f"{distribution.family} has no torch distribution for its arguments: "
            f"{error}"
        ) from error

site_morphism

site_morphism(distribution: RuntimeDistribution) -> ContinuousMorphism

The morphism a trace records for a site drawn from a distribution.

PARAMETER DESCRIPTION
distribution

The distribution the site was drawn from.

TYPE: RuntimeDistribution

RETURNS DESCRIPTION
ContinuousMorphism

A DrawnLaw of one position, inside a PlateDraw over the distribution's plate when it has one, so a registry reads the plate's positions and each position's event as it does for a plated site of a compiled program.

RAISES DESCRIPTION
DistributionError

If the family has no torch distribution for its arguments.

Source code in src/quivers/continuous/tensor_backend.py
def site_morphism(distribution: RuntimeDistribution) -> ContinuousMorphism:
    """The morphism a trace records for a site drawn from a distribution.

    Parameters
    ----------
    distribution : RuntimeDistribution
        The distribution the site was drawn from.

    Returns
    -------
    ContinuousMorphism
        A `DrawnLaw` of one position, inside a `PlateDraw` over the
        distribution's plate when it has one, so a registry reads the
        plate's positions and each position's event as it does for a
        plated site of a compiled program.

    Raises
    ------
    DistributionError
        If the family has no torch distribution for its arguments.
    """
    native = torch_law(distribution)
    plate = (*distribution.batch, *distribution.event)
    if not plate:
        return DrawnLaw(distribution, native)
    return PlateDraw(
        math.prod(plate),
        DrawnLaw(distribution, native),
        index_shape=plate,
    )