Skip to content

Distributions

RuntimeDistribution values sample and score distribution families on the reference machine, through the DistributionBackend of the run. The ReferenceBackend computes in plain Python numbers, position by position, through a HostLaw; the tensor backend computes with torch and keeps every gradient. A transpile target may support different families or parameterizations, which its support table lists.

distributions

Runtime distributions for the reference machine.

A :class:DistributionValue evaluates to a :class:RuntimeDistribution: the family's name, its named arguments as the machine holds them (numbers as tensors, nested distributions as runtime distributions), the plate it is constructed over, and the backend that samples and scores it. A backend takes the whole plated distribution, so a backend over a tensor library samples and scores every position of a plate at once.

Two backends ship. The reference backend here computes in plain Python, position by position, through family tables written independently of any tensor library, so a run can be compared against an independent oracle; it reads its arguments as host numbers and so has no derivative, and it refuses an argument that carries a gradient rather than detach it. The tensor backend of quivers.continuous.tensor_backend builds the family's torch distribution, as the compiled runtime does, and keeps every gradient; a run that is differentiated uses it.

HostLaw didactic-model

HostLaw(*, family: str, arguments: Mapping[str, HeldValue] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), batch: tuple[int, ...] = (), event: tuple[int, ...] = (), ranks: Mapping[str, int] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE), natural: tuple[int, ...] = ())

Bases: QiecModel

A constructed distribution whose arguments are host numbers.

The reference backend computes with Python numbers: it reads a RuntimeDistribution as a host law, whose arguments are numbers and nested tuples of numbers, and whose nested distributions are host laws too, and samples and scores it position by position through the family tables of this module. Parameter mappings are owned snapshots compared by identity. Plate extents and parameter ranks compare by value.

PARAMETER DESCRIPTION
family

The family's source name.

TYPE: str

arguments

The named parameters as host values; frozen on construction.

TYPE: Mapping[str, HeldValue] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

batch

The plate's batch extents, outermost first; each position is an independent draw scored on its own.

TYPE: tuple[int, ...] DEFAULT: ()

event

The plate's extended event extents, outermost first; draws along them join one event and are scored together.

TYPE: tuple[int, ...] DEFAULT: ()

ranks

Each parameter's own tensor rank, from the family registry, so an argument carrying plate dimensions can be told from one that does not.

TYPE: Mapping[str, int] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE)

natural

The family's own event extents, so a scalar given for a tensor parameter can be broadcast to the shape the family expects.

TYPE: tuple[int, ...] DEFAULT: ()

plated property

plated: bool

Whether the distribution is constructed over a plate.

RETURNS DESCRIPTION
bool

True when it has batch or extended event axes.

at

at(position: tuple[int, ...]) -> HostLaw

The distribution at one position of the plate, unplated.

PARAMETER DESCRIPTION
position

A position of the leading plate axes, outermost first; fewer positions than axes leave the remaining axes in place.

TYPE: tuple[int, ...]

RETURNS DESCRIPTION
HostLaw

The family with its arguments selected at the position and the selected axes dropped from the plate.

RAISES DESCRIPTION
DistributionError

If the position has more entries than the plate has axes.

Source code in src/quivers/qiec/distributions.py
def at(self, position: tuple[int, ...]) -> HostLaw:
    """The distribution at one position of the plate, unplated.

    Parameters
    ----------
    position : tuple[int, ...]
        A position of the leading plate axes, outermost first; fewer
        positions than axes leave the remaining axes in place.

    Returns
    -------
    HostLaw
        The family with its arguments selected at the position and
        the selected axes dropped from the plate.

    Raises
    ------
    DistributionError
        If the position has more entries than the plate has axes.
    """
    shape = (*self.batch, *self.event)
    if len(position) > len(shape):
        raise DistributionError(
            f"position {position!r} is deeper than a plate of rank {len(shape)}"
        )
    arguments = {
        name: self._broadcast(
            name,
            _slice_at(
                value, position, self.ranks.get(name, 0), plate_rank=len(shape)
            ),
        )
        for name, value in self.arguments.items()
    }
    remaining = len(position)
    batch = self.batch[remaining:] if remaining < len(self.batch) else ()
    event = self.event[max(remaining - len(self.batch), 0) :]
    return HostLaw(
        family=self.family,
        arguments=arguments,
        batch=batch,
        event=event,
        ranks=self.ranks,
        natural=self.natural,
    )

sample

sample(rng: Random | None = None) -> object

Draw one value from the family tables.

PARAMETER DESCRIPTION
rng

The generator to draw from; the module generator by default, which :func:seed_reference_rng controls.

TYPE: Random | None DEFAULT: None

RETURNS DESCRIPTION
object

The drawn host value: one draw of the family, or nested tuples of draws over the plate's batch and event axes.

RAISES DESCRIPTION
DistributionError

If the backend cannot sample the family.

Source code in src/quivers/qiec/distributions.py
def sample(self, rng: random.Random | None = None) -> object:
    """Draw one value from the family tables.

    Parameters
    ----------
    rng : random.Random | None
        The generator to draw from; the module generator by default,
        which :func:`seed_reference_rng` controls.

    Returns
    -------
    object
        The drawn host value: one draw of the family, or nested
        tuples of draws over the plate's batch and event axes.

    Raises
    ------
    DistributionError
        If the backend cannot sample the family.
    """
    generator = rng or _RNG
    if not self.plated:
        return _family_sample(self.family, self._at(()), generator)
    shape = (*self.batch, *self.event)
    return _nest(
        {
            position: _family_sample(self.family, self._at(position), generator)
            for position in _positions(shape)
        },
        shape,
    )

log_mass

log_mass(batch_axes: Literal[0] = 0) -> float
log_mass(batch_axes: int) -> object
log_mass(batch_axes: int = 0) -> object

The log of the distribution's total mass by the family tables.

PARAMETER DESCRIPTION
batch_axes

Number of leading independent batch axes retained in the result. The default totals the entire product measure.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
float or nested tuple

Zero for a probability measure; over a plate, the sum of the masses at every position, since the plate's draw is their product. Requested batch axes remain separate; event axes sum.

RAISES DESCRIPTION
DistributionError

If the retained rank is not an integer in the batch rank's range.

Source code in src/quivers/qiec/distributions.py
def log_mass(self, batch_axes: int = 0) -> object:
    """The log of the distribution's total mass by the family tables.

    Parameters
    ----------
    batch_axes : int
        Number of leading independent batch axes retained in the result.
        The default totals the entire product measure.

    Returns
    -------
    float or nested tuple
        Zero for a probability measure; over a plate, the sum of the
        masses at every position, since the plate's draw is their
        product. Requested batch axes remain separate; event axes sum.

    Raises
    ------
    DistributionError
        If the retained rank is not an integer in the batch rank's range.
    """
    if (
        isinstance(batch_axes, bool)
        or not isinstance(batch_axes, int)
        or not 0 <= batch_axes <= len(self.batch)
    ):
        raise DistributionError(
            "log_mass retained axes must be an integer within the batch rank"
        )
    if not self.plated:
        return _family_log_mass(self.family, self._at(()))
    shape = (*self.batch, *self.event)

    def total(prefix: tuple[int, ...]) -> float:
        """Sum independent log masses under one retained position.

        Parameters
        ----------
        prefix : tuple[int, ...]
            Position in retained batch axes.

        Returns
        -------
        float
            Log mass of the remaining independent product.
        """
        return math.fsum(
            _family_log_mass(self.family, self._at((*prefix, *position)))
            for position in _positions(shape[batch_axes:])
        )

    if not batch_axes:
        return total(())
    kept = shape[:batch_axes]
    return _nest({position: total(position) for position in _positions(kept)}, kept)

log_prob

log_prob(value: object, keep_batch: Literal[False] = False) -> float
log_prob(value: object, keep_batch: Literal[True]) -> object
log_prob(value: object, keep_batch: bool) -> object
log_prob(value: object, keep_batch: bool = False) -> object

Evaluate the log density at a value by the family tables.

PARAMETER DESCRIPTION
value

The point evaluated; over a plate, nested tuples of points shaped like the plate.

TYPE: object

keep_batch

Whether to keep one weight per batch position rather than total them.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
object

The log density as a float, or, with keep_batch over a batch, nested tuples of floats shaped like the batch axes.

RAISES DESCRIPTION
DistributionError

If the backend cannot score the family, or the point is not shaped like the plate.

Source code in src/quivers/qiec/distributions.py
def log_prob(self, value: object, keep_batch: bool = False) -> object:
    """Evaluate the log density at a value by the family tables.

    Parameters
    ----------
    value : object
        The point evaluated; over a plate, nested tuples of points
        shaped like the plate.
    keep_batch : bool
        Whether to keep one weight per batch position rather than
        total them.

    Returns
    -------
    object
        The log density as a float, or, with ``keep_batch`` over a
        batch, nested tuples of floats shaped like the batch axes.

    Raises
    ------
    DistributionError
        If the backend cannot score the family, or the point is not
        shaped like the plate.
    """
    if not self.plated:
        return _family_log_prob(self.family, self._at(()), value)
    shape = (*self.batch, *self.event)
    if tensor_rank(value) < len(shape):
        raise DistributionError(
            f"a point scored under a plate of rank {len(shape)} has rank "
            f"{tensor_rank(value)}"
        )
    totals: dict[tuple[int, ...], float] = {
        position: 0.0 for position in _positions(self.batch)
    }
    for position in _positions(shape):
        point = value
        for index in position:
            point = point[index]  # type: ignore[index]
        totals[position[: len(self.batch)]] += _family_log_prob(
            self.family, self._at(position), point
        )
    if keep_batch:
        return _nest(totals, self.batch)
    return math.fsum(totals.values())

DistributionBackend

Bases: Protocol

What samples and scores the runtime distributions of a run.

differentiable property

differentiable: bool

Whether densities and reparameterized draws keep their gradients.

RETURNS DESCRIPTION
bool

True for a backend whose results are differentiable in the arguments.

sample

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

Draw one value at every position of the plate.

PARAMETER DESCRIPTION
distribution

The distribution.

TYPE: RuntimeDistribution

rng

The host generator, for a backend that draws in host numbers.

TYPE: Random

RETURNS DESCRIPTION
object

The draw as the machine holds it: a tensor shaped by the plate's batch and event axes followed by the family's own.

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

    Parameters
    ----------
    distribution : RuntimeDistribution
        The distribution.
    rng : random.Random
        The host generator, for a backend that draws in host numbers.

    Returns
    -------
    object
        The draw as the machine holds it: a tensor shaped by the
        plate's batch and event axes followed by the family's own.
    """
    ...

log_prob

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

Evaluate the log density at a value.

PARAMETER DESCRIPTION
distribution

The distribution.

TYPE: RuntimeDistribution

value

The point, shaped like a draw.

TYPE: object

keep_batch

Whether to keep one density per batch position rather than total them; event axes are always totalled.

TYPE: bool

RETURNS DESCRIPTION
Tensor

The log density, of the run's real dtype.

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

    Parameters
    ----------
    distribution : RuntimeDistribution
        The distribution.
    value : object
        The point, shaped like a draw.
    keep_batch : bool
        Whether to keep one density per batch position rather than
        total them; event axes are always totalled.

    Returns
    -------
    torch.Tensor
        The log density, of the run's real dtype.
    """
    ...

log_mass

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

The log of the total mass of a construction.

PARAMETER DESCRIPTION
distribution

The distribution.

TYPE: RuntimeDistribution

batch_axes

The leading batch axes kept in the result.

TYPE: int

RETURNS DESCRIPTION
Tensor

Zero for a probability measure; the log mass of a restriction or of a mixture of restrictions, which Normalize divides by.

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

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

    Returns
    -------
    torch.Tensor
        Zero for a probability measure; the log mass of a restriction
        or of a mixture of restrictions, which ``Normalize`` divides
        by.
    """
    ...

RuntimeDistribution didactic-model

RuntimeDistribution(*, backend: DistributionBackend = field(opaque=True, extras=OPAQUE_BY_IDENTITY), numbers: NumberDomain, family: str, arguments: Mapping[str, HeldValue] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), batch: tuple[int, ...] = (), event: tuple[int, ...] = (), ranks: Mapping[str, int] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE), natural: tuple[int, ...] = ())

Bases: QiecModel

A constructed distribution, as the machine holds it.

The backend, the argument mapping and its values retain identity, so a tensor argument keeps its gradient; plate extents and parameter ranks compare by value.

PARAMETER DESCRIPTION
backend

What samples and scores the distribution.

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

numbers

The run's numbers, which hold its draws and densities.

TYPE: NumberDomain

family

The family's source name.

TYPE: str

arguments

The named parameters: tensors, or runtime distributions for a family built from other distributions; frozen on construction.

TYPE: Mapping[str, HeldValue] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

batch

The plate's batch extents, outermost first; each position is an independent draw scored on its own.

TYPE: tuple[int, ...] DEFAULT: ()

event

The plate's extended event extents, outermost first; draws along them join one event and are scored together.

TYPE: tuple[int, ...] DEFAULT: ()

ranks

Each parameter's own tensor rank, from the family registry, so an argument carrying plate dimensions can be told from one that does not.

TYPE: Mapping[str, int] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE)

natural

The family's own event extents, so a scalar given for a tensor parameter can be broadcast to the shape the family expects.

TYPE: tuple[int, ...] DEFAULT: ()

plated property

plated: bool

Whether the distribution is constructed over a plate.

RETURNS DESCRIPTION
bool

True when it has batch or extended event axes.

sample

sample(rng: Random | None = None) -> object

Draw one value at every position of the plate.

PARAMETER DESCRIPTION
rng

The host generator a backend drawing in host numbers uses; the module generator by default, which :func:seed_reference_rng controls.

TYPE: Random | None DEFAULT: None

RETURNS DESCRIPTION
object

The draw as the machine holds it.

RAISES DESCRIPTION
DistributionError

If the backend cannot sample the family.

Source code in src/quivers/qiec/distributions.py
def sample(self, rng: random.Random | None = None) -> object:
    """Draw one value at every position of the plate.

    Parameters
    ----------
    rng : random.Random | None
        The host generator a backend drawing in host numbers uses; the
        module generator by default, which :func:`seed_reference_rng`
        controls.

    Returns
    -------
    object
        The draw as the machine holds it.

    Raises
    ------
    DistributionError
        If the backend cannot sample the family.
    """
    return self.backend.sample(self, rng or _RNG)

log_mass

log_mass(batch_axes: int = 0) -> Tensor

The log of the distribution's total mass.

PARAMETER DESCRIPTION
batch_axes

Number of leading independent batch axes retained in the result. The default totals the entire product measure.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
Tensor

Zero for a probability measure; over a plate, the sum of the masses at every position, since the plate's draw is their product. Requested batch axes remain separate; event axes sum.

RAISES DESCRIPTION
DistributionError

If the retained rank is not an integer in the batch rank's range.

Source code in src/quivers/qiec/distributions.py
def log_mass(self, batch_axes: int = 0) -> torch.Tensor:
    """The log of the distribution's total mass.

    Parameters
    ----------
    batch_axes : int
        Number of leading independent batch axes retained in the result.
        The default totals the entire product measure.

    Returns
    -------
    torch.Tensor
        Zero for a probability measure; over a plate, the sum of the
        masses at every position, since the plate's draw is their
        product. Requested batch axes remain separate; event axes sum.

    Raises
    ------
    DistributionError
        If the retained rank is not an integer in the batch rank's range.
    """
    if (
        isinstance(batch_axes, bool)
        or not isinstance(batch_axes, int)
        or not 0 <= batch_axes <= len(self.batch)
    ):
        raise DistributionError(
            "log_mass retained axes must be an integer within the batch rank"
        )
    return self.backend.log_mass(self, batch_axes)

log_prob

log_prob(value: object, keep_batch: bool = False) -> Tensor

Evaluate the log density at a value.

PARAMETER DESCRIPTION
value

The point evaluated; over a plate, shaped like the plate followed by the family's own axes.

TYPE: object

keep_batch

Whether to keep one weight per batch position rather than total them.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Tensor

The log density, or, with keep_batch over a batch, one per batch position.

RAISES DESCRIPTION
DistributionError

If the backend cannot score the family, or the point is not shaped like the plate.

Source code in src/quivers/qiec/distributions.py
def log_prob(self, value: object, keep_batch: bool = False) -> torch.Tensor:
    """Evaluate the log density at a value.

    Parameters
    ----------
    value : object
        The point evaluated; over a plate, shaped like the plate
        followed by the family's own axes.
    keep_batch : bool
        Whether to keep one weight per batch position rather than
        total them.

    Returns
    -------
    torch.Tensor
        The log density, or, with ``keep_batch`` over a batch, one per
        batch position.

    Raises
    ------
    DistributionError
        If the backend cannot score the family, or the point is not
        shaped like the plate.
    """
    return self.backend.log_prob(self, value, keep_batch)

ReferenceBackend

Plain-Python sampling and scoring for every family of the registry.

The scalar core lives beside the backend and the structured and compositional families in :mod:quivers.qiec.reference_families; a family outside the tables is reported by name rather than approximated. It reads a runtime distribution as a HostLaw, computes in host numbers position by position, and gives its results back as tensors of the run's numbers; an argument or a point that carries a gradient is refused.

differentiable property

differentiable: bool

No: the backend computes in host numbers.

RETURNS DESCRIPTION
bool

False.

families property

families: frozenset[str]

The families this backend implements.

RETURNS DESCRIPTION
frozenset[str]

The family names.

family_sample

family_sample(family: str, arguments: Mapping[str, object], rng: Random) -> object

Draw one value of a family from host arguments.

PARAMETER DESCRIPTION
family

The family's source name.

TYPE: str

arguments

The named parameters as host values.

TYPE: Mapping[str, object]

rng

The generator to draw from.

TYPE: Random

RETURNS DESCRIPTION
object

The drawn host value.

RAISES DESCRIPTION
DistributionError

If the family is not implemented here or a parameter is missing or malformed.

Source code in src/quivers/qiec/distributions.py
def family_sample(
    self, family: str, arguments: Mapping[str, object], rng: random.Random
) -> object:
    """Draw one value of a family from host arguments.

    Parameters
    ----------
    family : str
        The family's source name.
    arguments : Mapping[str, object]
        The named parameters as host values.
    rng : random.Random
        The generator to draw from.

    Returns
    -------
    object
        The drawn host value.

    Raises
    ------
    DistributionError
        If the family is not implemented here or a parameter is
        missing or malformed.
    """
    return _family_sample(family, arguments, rng)

family_log_prob

family_log_prob(family: str, arguments: Mapping[str, object], value: object) -> float

Evaluate the log density of a family from host arguments.

PARAMETER DESCRIPTION
family

The family's source name.

TYPE: str

arguments

The named parameters as host values.

TYPE: Mapping[str, object]

value

The point evaluated.

TYPE: object

RETURNS DESCRIPTION
float

The log density, -inf outside the support.

RAISES DESCRIPTION
DistributionError

If the family is not implemented here or a parameter or the point is malformed.

Source code in src/quivers/qiec/distributions.py
def family_log_prob(
    self, family: str, arguments: Mapping[str, object], value: object
) -> float:
    """Evaluate the log density of a family from host arguments.

    Parameters
    ----------
    family : str
        The family's source name.
    arguments : Mapping[str, object]
        The named parameters as host values.
    value : object
        The point evaluated.

    Returns
    -------
    float
        The log density, ``-inf`` outside the support.

    Raises
    ------
    DistributionError
        If the family is not implemented here or a parameter or the
        point is malformed.
    """
    return _family_log_prob(family, arguments, value)

family_log_mass

family_log_mass(family: str, arguments: Mapping[str, object]) -> float

The log of the total mass of a construction from host arguments.

PARAMETER DESCRIPTION
family

The family's source name.

TYPE: str

arguments

The named parameters as host values.

TYPE: Mapping[str, object]

RETURNS DESCRIPTION
float

The family's log mass, zero for every probability family.

RAISES DESCRIPTION
DistributionError

If the family is not implemented here.

Source code in src/quivers/qiec/distributions.py
def family_log_mass(self, family: str, arguments: Mapping[str, object]) -> float:
    """The log of the total mass of a construction from host arguments.

    Parameters
    ----------
    family : str
        The family's source name.
    arguments : Mapping[str, object]
        The named parameters as host values.

    Returns
    -------
    float
        The family's log mass, zero for every probability family.

    Raises
    ------
    DistributionError
        If the family is not implemented here.
    """
    return _family_log_mass(family, arguments)

sample

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

Draw at every position of the plate, in host numbers.

PARAMETER DESCRIPTION
distribution

The distribution.

TYPE: RuntimeDistribution

rng

The generator.

TYPE: Random

RETURNS DESCRIPTION
object

The draw as a tensor of the family's element kind.

RAISES DESCRIPTION
DistributionError

If the family is not implemented here or an argument carries a gradient.

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

    Parameters
    ----------
    distribution : RuntimeDistribution
        The distribution.
    rng : random.Random
        The generator.

    Returns
    -------
    object
        The draw as a tensor of the family's element kind.

    Raises
    ------
    DistributionError
        If the family is not implemented here or an argument carries a
        gradient.
    """
    drawn = _host_law(distribution).sample(rng)
    element = family_record(distribution.family).element
    return machine_value(element, drawn, distribution.numbers)

log_prob

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

Evaluate the log density in host numbers.

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.

RAISES DESCRIPTION
DistributionError

If the family is not implemented here, or an argument or the point carries a gradient.

Source code in src/quivers/qiec/distributions.py
def log_prob(
    self, distribution: RuntimeDistribution, value: object, keep_batch: bool
) -> torch.Tensor:
    """Evaluate the log density in host numbers.

    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.

    Raises
    ------
    DistributionError
        If the family is not implemented here, or an argument or the
        point carries a gradient.
    """
    density = _host_law(distribution).log_prob(
        _point(value, distribution.family), keep_batch
    )
    return torch.tensor(
        density,
        dtype=distribution.numbers.real_dtype,
        device=distribution.numbers.torch_device,
    )

log_mass

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

The log total mass in host numbers.

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 is not implemented here or an argument carries a gradient.

Source code in src/quivers/qiec/distributions.py
def log_mass(
    self, distribution: RuntimeDistribution, batch_axes: int
) -> torch.Tensor:
    """The log total mass in host numbers.

    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 is not implemented here or an argument carries a
        gradient.
    """
    return torch.tensor(
        _host_law(distribution).log_mass(batch_axes),
        dtype=distribution.numbers.real_dtype,
        device=distribution.numbers.torch_device,
    )

tensor_rank

tensor_rank(value: object) -> int

The nesting depth of a host tensor.

PARAMETER DESCRIPTION
value

A host value: a scalar, or a tuple of values of one rank.

TYPE: object

RETURNS DESCRIPTION
int

Zero for a scalar, one more than the first entry's rank for a tuple; an empty tuple has rank one.

Source code in src/quivers/qiec/distributions.py
def tensor_rank(value: object) -> int:
    """The nesting depth of a host tensor.

    Parameters
    ----------
    value : object
        A host value: a scalar, or a tuple of values of one rank.

    Returns
    -------
    int
        Zero for a scalar, one more than the first entry's rank for a
        tuple; an empty tuple has rank one.
    """
    if isinstance(value, tuple):
        return 1 + (tensor_rank(value[0]) if value else 0)
    return 0

seed_reference_rng

seed_reference_rng(seed: int) -> None

Reseed the generator reference draws use by default.

PARAMETER DESCRIPTION
seed

The seed; two runs seeded alike draw alike.

TYPE: int

Source code in src/quivers/qiec/distributions.py
def seed_reference_rng(seed: int) -> None:
    """Reseed the generator reference draws use by default.

    Parameters
    ----------
    seed : int
        The seed; two runs seeded alike draw alike.
    """
    _RNG.seed(seed)

distribution_backend

distribution_backend() -> DistributionBackend

The backend distribution values currently sample and score through.

RETURNS DESCRIPTION
DistributionBackend

The installed backend; the reference backend until replaced.

Source code in src/quivers/qiec/distributions.py
def distribution_backend() -> DistributionBackend:
    """The backend distribution values currently sample and score through.

    Returns
    -------
    DistributionBackend
        The installed backend; the reference backend until replaced.
    """
    return _backend

install_distribution_backend

install_distribution_backend(backend: DistributionBackend) -> DistributionBackend

Replace the backend distribution values sample and score through.

PARAMETER DESCRIPTION
backend

The backend to install, such as one over a host library that covers every family.

TYPE: DistributionBackend

RETURNS DESCRIPTION
DistributionBackend

The backend that was installed before, so a caller can restore it.

Source code in src/quivers/qiec/distributions.py
def install_distribution_backend(backend: DistributionBackend) -> DistributionBackend:
    """Replace the backend distribution values sample and score through.

    Parameters
    ----------
    backend : DistributionBackend
        The backend to install, such as one over a host library that
        covers every family.

    Returns
    -------
    DistributionBackend
        The backend that was installed before, so a caller can restore it.
    """
    global _backend
    previous = _backend
    _backend = backend
    return previous

Finite structured sampleables

A FiniteSampleable is a normalized law on an explicit list of closed discrete QIEC values. A provider can supply it to a checked Sampleable[A] parameter, where A is the declared type of its points. A regular recursive family can be the carrier. The list specifies the complete candidate support of this law.

For a point \(x\) and input log weights \(w_i\), the probability is

\[ P(x) = \frac{\sum_{i\colon x_i = x} \exp(w_i - m)} {\sum_i \exp(w_i - m)}, \qquad m = \max_i w_i. \]

The runtime uses exact structural equality on this carrier. Equal constructors compare by nominal identity and ordered fields. Equal points share one probability. An input log weight of \(-\infty\) contributes zero. An empty support or zero total mass cannot be normalized. Centering prevents a common offset from swamping the log normalizer. A finite difference outside the run's numerical range raises a distribution error.

Drawing uses the ordinary categorical sampler and follows its numerical and randomness conventions. Scoring, conditioning, and replay use the normalized log probability and keep its weight gradient. Exact enumeration visits each positive-mass value once, using the existing Random enumeration handler. An unrestricted resumption must have an explicit provider assertion that any captured law may be duplicated, as it does for other opaque runtime values. The provider may share this law between shots when its support and weights stay fixed during that invocation. A later run reads the live weights again.

For \(n\) weight occurrences and \(k\) distinct candidates, indexing the support validates the reachable carrier declarations and hashes the input term data. A density query also checks and hashes its argument. A score or enumeration reads \(n\) weights in total and uses \(O(n + k)\) temporary storage. Enumeration adds the cost of running the continuation for each positive-mass value. The law has scalar log probabilities and one term-valued draw. It has no plate axes or reparameterized sampling rule.

An exact finite posterior

The existing enumeration handler can also retain one scalar log joint per point. With Enumeration(reduction="table", grouped=True), the handled computation returns its observation log likelihood together with its value. For one sampled structured site, the table's order is the order of prior.weighted_support(), and its declared extent must equal the number of positive-mass prior points. A provider can use the returned table as the log weights of a law on those same points.

support = tuple(point for point, _ in prior.weighted_support())
posterior = prior.with_(values=support, log_weights=table)

The exponentiated entries sum to the evidence. The resulting law normalizes it to the exact posterior for the declared finite support. Scoring that posterior preserves the gradient with respect to both the prior weights and the observation law.

structured_sampleables

Finite sampleables whose points are closed discrete QIEC values.

FiniteSampleable didactic-model

FiniteSampleable(*, element: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE), values: tuple[object, ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), log_weights: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), registry: KernelRegistry = field(opaque=True, extras=OPAQUE_BY_IDENTITY), backend: DistributionBackend | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

A normalized distribution on explicit closed discrete QIEC values.

Equal points share one mass, obtained by adding the masses of their occurrences. Zero-mass points are absent from enumeration and a typed point outside the positive support has log probability negative infinity. Generation draws once from the finite law. Enumeration and scoring share the same normalization. The log weights retain their gradient and are read afresh at every request.

PARAMETER DESCRIPTION
element

The closed discrete QIEC type of each point. Regular recursive families with ordinary constructors are admitted.

TYPE: TypeExpr DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

values

The candidate points as checked runtime values. Treat these discrete values as immutable for the lifetime of the sampleable.

TYPE: tuple[object, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

log_weights

One unnormalized log mass for each candidate, in order. The tensor is retained by identity. No batch or plate axes are used.

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

registry

The checked declaration registry for the nominal types and constructors.

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

backend

An explicit backend override. A request otherwise uses the backend of its invocation to draw the categorical index.

TYPE: DistributionBackend | None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

numbers property

numbers: NumberDomain

The dtype and device shared by the law's log probabilities.

RETURNS DESCRIPTION
NumberDomain

The number domain of the supplied log weights.

log_mass

log_mass(batch_axes: int = 0) -> Tensor

Return the log total mass of the normalized law.

PARAMETER DESCRIPTION
batch_axes

Retained batch rank, which must be zero for this unbatched law.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
Tensor

Scalar zero in the law's number domain.

RAISES DESCRIPTION
DistributionError

If a retained batch axis is requested or the live mass is invalid.

Source code in src/quivers/qiec/structured_sampleables.py
def log_mass(self, batch_axes: int = 0) -> torch.Tensor:
    """Return the log total mass of the normalized law.

    Parameters
    ----------
    batch_axes
        Retained batch rank, which must be zero for this unbatched law.

    Returns
    -------
    torch.Tensor
        Scalar zero in the law's number domain.

    Raises
    ------
    DistributionError
        If a retained batch axis is requested or the live mass is invalid.
    """
    if isinstance(batch_axes, bool) or batch_axes != 0:
        raise DistributionError("finite sampleables do not have batch axes")
    self._centered_weights()
    return self.numbers.zero()

log_prob

log_prob(value: object, keep_batch: bool = False) -> Tensor

Score one typed value under the current normalized law.

PARAMETER DESCRIPTION
value

A typed value of this law's element type.

TYPE: object

keep_batch

Whether to keep independent batch axes. This law has no such axes.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Tensor

The scalar log probability, or negative infinity outside the support.

Source code in src/quivers/qiec/structured_sampleables.py
def log_prob(self, value: object, keep_batch: bool = False) -> torch.Tensor:
    """Score one typed value under the current normalized law.

    Parameters
    ----------
    value
        A typed value of this law's element type.
    keep_batch
        Whether to keep independent batch axes. This law has no such axes.

    Returns
    -------
    torch.Tensor
        The scalar log probability, or negative infinity outside the support.
    """
    del keep_batch
    weights = self._centered_weights()
    key = self._key(value)
    group = self._groups.get(key)
    if group is None:
        return self.log_weights.new_full((), -torch.inf)
    return LOG_PROB.join(weights[list(group)], 0) - LOG_PROB.join(weights, 0)

weighted_support

weighted_support() -> tuple[tuple[object, Tensor], ...]

Return every positive-support value with normalized log probability.

RETURNS DESCRIPTION
tuple

Distinct points and their scalar log probabilities, in first-occurrence order.

Source code in src/quivers/qiec/structured_sampleables.py
def weighted_support(self) -> tuple[tuple[object, torch.Tensor], ...]:
    """Return every positive-support value with normalized log probability.

    Returns
    -------
    tuple
        Distinct points and their scalar log probabilities, in
        first-occurrence order.
    """
    weights = self._centered_weights()
    normalizer = LOG_PROB.join(weights, 0)
    result = []
    for indices in self._groups.values():
        mass = LOG_PROB.join(weights[list(indices)], 0)
        if decide(torch.isfinite(mass), "finite sampleable support"):
            result.append((self.values[indices[0]], mass - normalizer))
    return tuple(result)

sample

sample(*, backend: DistributionBackend | None = None) -> object

Draw one value with the ordinary categorical distribution backend.

PARAMETER DESCRIPTION
backend

The invocation's backend. An explicit override on the law takes precedence, and the installed backend serves a draw outside an invocation.

TYPE: DistributionBackend | None DEFAULT: None

RETURNS DESCRIPTION
object

One point of the checked element type.

Source code in src/quivers/qiec/structured_sampleables.py
def sample(self, *, backend: DistributionBackend | None = None) -> object:
    """Draw one value with the ordinary categorical distribution backend.

    Parameters
    ----------
    backend
        The invocation's backend. An explicit override on the law
        takes precedence, and the installed backend serves a draw
        outside an invocation.

    Returns
    -------
    object
        One point of the checked element type.
    """
    with torch.no_grad():
        support = self.weighted_support()
        distribution = RuntimeDistribution(
            backend=self.backend or backend or distribution_backend(),
            numbers=self.numbers,
            family="Categorical",
            arguments={"logits": torch.stack([weight for _, weight in support])},
            ranks={"logits": 1},
        )
        index = host_index(distribution.sample(), "finite categorical draw")
    return support[index][0]