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:
|
arguments
|
The named parameters as host values; frozen on construction.
TYPE:
|
batch
|
The plate's batch extents, outermost first; each position is an independent draw scored on its own.
TYPE:
|
event
|
The plate's extended event extents, outermost first; draws along them join one event and are scored together.
TYPE:
|
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:
|
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:
|
plated
property
¶
Whether the distribution is constructed over a plate.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
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:
|
| 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
sample
¶
Draw one value from the family tables.
| PARAMETER | DESCRIPTION |
|---|---|
rng
|
The generator to draw from; the module generator by default,
which :func:
TYPE:
|
| 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
log_mass
¶
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:
|
| 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
log_prob
¶
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:
|
keep_batch
|
Whether to keep one weight per batch position rather than total them.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
object
|
The log density as a float, or, with |
| 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
DistributionBackend
¶
Bases: Protocol
What samples and scores the runtime distributions of a run.
differentiable
property
¶
Whether densities and reparameterized draws keep their gradients.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
sample
¶
sample(distribution: RuntimeDistribution, rng: Random) -> object
Draw one value at every position of the plate.
| PARAMETER | DESCRIPTION |
|---|---|
distribution
|
The distribution.
TYPE:
|
rng
|
The host generator, for a backend that draws in host numbers.
TYPE:
|
| 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
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:
|
value
|
The point, shaped like a draw.
TYPE:
|
keep_batch
|
Whether to keep one density per batch position rather than total them; event axes are always totalled.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The log density, of the run's real dtype. |
Source code in src/quivers/qiec/distributions.py
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:
|
batch_axes
|
The leading batch axes kept in the result.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Zero for a probability measure; the log mass of a restriction
or of a mixture of restrictions, which |
Source code in src/quivers/qiec/distributions.py
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:
|
numbers
|
The run's numbers, which hold its draws and densities.
TYPE:
|
family
|
The family's source name.
TYPE:
|
arguments
|
The named parameters: tensors, or runtime distributions for a family built from other distributions; frozen on construction.
TYPE:
|
batch
|
The plate's batch extents, outermost first; each position is an independent draw scored on its own.
TYPE:
|
event
|
The plate's extended event extents, outermost first; draws along them join one event and are scored together.
TYPE:
|
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:
|
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:
|
plated
property
¶
Whether the distribution is constructed over a plate.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
sample
¶
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:
TYPE:
|
| 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
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:
|
| 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
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:
|
keep_batch
|
Whether to keep one weight per batch position rather than total them.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The log density, or, with |
| 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
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
¶
No: the backend computes in host numbers.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
families
property
¶
The families this backend implements.
| RETURNS | DESCRIPTION |
|---|---|
frozenset[str]
|
The family names. |
family_sample
¶
Draw one value of a family from host arguments.
| PARAMETER | DESCRIPTION |
|---|---|
family
|
The family's source name.
TYPE:
|
arguments
|
The named parameters as host values.
TYPE:
|
rng
|
The generator to draw from.
TYPE:
|
| 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
family_log_prob
¶
Evaluate the log density of a family from host arguments.
| PARAMETER | DESCRIPTION |
|---|---|
family
|
The family's source name.
TYPE:
|
arguments
|
The named parameters as host values.
TYPE:
|
value
|
The point evaluated.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
The log density, |
| 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
family_log_mass
¶
The log of the total mass of a construction from host arguments.
| PARAMETER | DESCRIPTION |
|---|---|
family
|
The family's source name.
TYPE:
|
arguments
|
The named parameters as host values.
TYPE:
|
| 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
sample
¶
sample(distribution: RuntimeDistribution, rng: Random) -> object
Draw at every position of the plate, in host numbers.
| PARAMETER | DESCRIPTION |
|---|---|
distribution
|
The distribution.
TYPE:
|
rng
|
The generator.
TYPE:
|
| 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
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:
|
value
|
The point.
TYPE:
|
keep_batch
|
Whether to keep one density per batch position.
TYPE:
|
| 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
log_mass
¶
log_mass(distribution: RuntimeDistribution, batch_axes: int) -> Tensor
The log total mass in host numbers.
| PARAMETER | DESCRIPTION |
|---|---|
distribution
|
The distribution.
TYPE:
|
batch_axes
|
The leading batch axes kept.
TYPE:
|
| 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
tensor_rank
¶
The nesting depth of a host tensor.
| PARAMETER | DESCRIPTION |
|---|---|
value
|
A host value: a scalar, or a tuple of values of one rank.
TYPE:
|
| 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
seed_reference_rng
¶
Reseed the generator reference draws use by default.
| PARAMETER | DESCRIPTION |
|---|---|
seed
|
The seed; two runs seeded alike draw alike.
TYPE:
|
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
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:
|
| RETURNS | DESCRIPTION |
|---|---|
DistributionBackend
|
The backend that was installed before, so a caller can restore it. |
Source code in src/quivers/qiec/distributions.py
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
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:
|
values
|
The candidate points as checked runtime values. Treat these discrete values as immutable for the lifetime of the sampleable.
TYPE:
|
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:
|
registry
|
The checked declaration registry for the nominal types and constructors.
TYPE:
|
backend
|
An explicit backend override. A request otherwise uses the backend of its invocation to draw the categorical index.
TYPE:
|
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:
|
| 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
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:
|
keep_batch
|
Whether to keep independent batch axes. This law has no such axes.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The scalar log probability, or negative infinity outside the support. |
Source code in src/quivers/qiec/structured_sampleables.py
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
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:
|
| RETURNS | DESCRIPTION |
|---|---|
object
|
One point of the checked element type. |