Skip to content

Sampleables

A MonadicProgram step draws from a ContinuousMorphism at an input tensor, and the Quivers Indexed Effect Core (QIEC) request Random.sample takes one sampleable value. TorchSampleable wraps the pair as that value (sample sites). It offers the sampling and scoring interface the prelude handlers use, and keeps the morphism and the input for a strategy or a trace to read.

sites

Host sampleables: a torch morphism applied to an input, as a distribution.

A MonadicProgram step draws from a ContinuousMorphism at an input tensor. The kernel's Random.sample request takes a sampleable value, so the pair is wrapped as one: TorchSampleable offers the sampling and scoring interface the prelude handlers use and keeps the morphism and input a strategy or a trace may want to read.

TorchSampleable

TorchSampleable(*, morphism: ContinuousMorphism, input: Tensor, declared: ContinuousMorphism | None = None, raw_morphism: ContinuousMorphism | None = None)

Bases: ValueModel

A morphism applied to an input, offered to the kernel as a sampleable.

PARAMETER DESCRIPTION
morphism

The morphism the site draws from, under whatever parameters the run's Param handlers answered.

TYPE: ContinuousMorphism

input

The input tensor the morphism is conditioned on, carrying the batch axis.

TYPE: Tensor

declared

The morphism as the program declares it, which a trace records and a strategy reads the family of; the drawing morphism itself when no parameter store rebinds it.

TYPE: ContinuousMorphism | None DEFAULT: None

raw_morphism

The parameterized response distribution before likelihood weighting or observation subsampling, used for raw likelihood extraction.

TYPE: ContinuousMorphism | None DEFAULT: None

Construct a sampleable holding live runtime references by identity.

PARAMETER DESCRIPTION
morphism

The morphism used for sampling and scoring.

TYPE: ContinuousMorphism

input

The tensor conditioning the morphism.

TYPE: Tensor

declared

The declared site morphism, defaulting to the sampling morphism.

TYPE: ContinuousMorphism or None DEFAULT: None

raw_morphism

The unweighted response morphism, defaulting to the sampling morphism.

TYPE: ContinuousMorphism or None DEFAULT: None

RAISES DESCRIPTION
ValidationError

If the runtime fields have incompatible types.

Source code in src/quivers/effects/sites.py
def __init__(
    self,
    *,
    morphism: ContinuousMorphism,
    input: torch.Tensor,
    declared: ContinuousMorphism | None = None,
    raw_morphism: ContinuousMorphism | None = None,
) -> None:
    """Construct a sampleable holding live runtime references by identity.

    Parameters
    ----------
    morphism : ContinuousMorphism
        The morphism used for sampling and scoring.
    input : torch.Tensor
        The tensor conditioning the morphism.
    declared : ContinuousMorphism or None
        The declared site morphism, defaulting to the sampling morphism.
    raw_morphism : ContinuousMorphism or None
        The unweighted response morphism, defaulting to the sampling morphism.

    Raises
    ------
    didactic.ValidationError
        If the runtime fields have incompatible types.
    """
    initialize = cast("Callable[..., None]", super().__init__)
    initialize(
        morphism=morphism,
        input=input,
        declared=morphism if declared is None else declared,
        raw_morphism=morphism if raw_morphism is None else raw_morphism,
    )

rsample

rsample() -> Tensor

Draw a reparameterised sample.

RETURNS DESCRIPTION
Tensor

One draw per batch row.

Source code in src/quivers/effects/sites.py
def rsample(self) -> torch.Tensor:
    """Draw a reparameterised sample.

    Returns
    -------
    torch.Tensor
        One draw per batch row.
    """
    return self.morphism.rsample(self.input)

sample

sample() -> Tensor

Draw a sample.

RETURNS DESCRIPTION
Tensor

One draw per batch row.

Source code in src/quivers/effects/sites.py
def sample(self) -> torch.Tensor:
    """Draw a sample.

    Returns
    -------
    torch.Tensor
        One draw per batch row.
    """
    return self.morphism.rsample(self.input)

log_prob

log_prob(value: Tensor) -> Tensor

Score a value under the morphism at the input.

PARAMETER DESCRIPTION
value

The value, one per batch row.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The log density per batch row.

Source code in src/quivers/effects/sites.py
def log_prob(self, value: torch.Tensor) -> torch.Tensor:
    """Score a value under the morphism at the input.

    Parameters
    ----------
    value : torch.Tensor
        The value, one per batch row.

    Returns
    -------
    torch.Tensor
        The log density per batch row.
    """
    return self.morphism.log_prob(self.input, value)

parameters

parameters() -> dict[str, Tensor]

The distribution parameters the morphism computes at the input.

RETURNS DESCRIPTION
dict[str, Tensor]

The named parameters of the torch distribution the morphism builds, or loc and scale for a morphism that exposes only a location-scale pair.

RAISES DESCRIPTION
TypeError

If the morphism exposes neither a distribution builder nor a location-scale pair.

Source code in src/quivers/effects/sites.py
def parameters(self) -> dict[str, torch.Tensor]:
    """The distribution parameters the morphism computes at the input.

    Returns
    -------
    dict[str, torch.Tensor]
        The named parameters of the torch distribution the morphism
        builds, or ``loc`` and ``scale`` for a morphism that exposes
        only a location-scale pair.

    Raises
    ------
    TypeError
        If the morphism exposes neither a distribution builder nor a
        location-scale pair.
    """
    get_dist = getattr(self.morphism, "_get_dist", None)
    if callable(get_dist):
        distribution = get_dist(self.input)
        return {
            name: getattr(distribution, name)
            for name in distribution.arg_constraints
            if hasattr(distribution, name)
        }
    get_params = getattr(self.morphism, "_get_params", None)
    if callable(get_params):
        loc, scale = get_params(self.input)
        return {"loc": loc, "scale": scale}
    raise TypeError(
        f"{type(self.morphism).__name__} exposes no distribution parameters"
    )

raw_log_prob_pointwise

raw_log_prob_pointwise(value: Tensor) -> Tensor

Read the response density before likelihood weighting or subsampling.

PARAMETER DESCRIPTION
value

The observed response values.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Raw log densities, one per observation row when the family has a plate, with event dimensions reduced.

RAISES DESCRIPTION
TypeError

If the site is the response of a marginalized block, whose density the units of the block's score hold.

Source code in src/quivers/effects/sites.py
def raw_log_prob_pointwise(self, value: torch.Tensor) -> torch.Tensor:
    """Read the response density before likelihood weighting or subsampling.

    Parameters
    ----------
    value : torch.Tensor
        The observed response values.

    Returns
    -------
    torch.Tensor
        Raw log densities, one per observation row when the family has
        a plate, with event dimensions reduced.

    Raises
    ------
    TypeError
        If the site is the response of a marginalized block, whose
        density the units of the block's score hold.
    """
    if isinstance(self.declared, MarginalizedFactor):
        raise TypeError(
            "this observation has no density of its own: the score of the "
            "block that sums its latent out holds it, by unit"
        )
    pointwise = getattr(self.raw_morphism, "log_prob_pointwise", None)
    if callable(pointwise):
        result = pointwise(self.input, value)
        assert isinstance(result, torch.Tensor)
        return result
    return self.raw_morphism.log_prob(self.input, value)