Continuous Programs¶
A MonadicProgram is a probabilistic program over continuous and discrete spaces: a sequence of
draws, observations, and deterministic computations with named intermediate values, in which
later steps read earlier values
(Moggi, 1991; Giry, 1982) (building programs in Python).
Running a program records its latent draws and observation scores in an
execution trace, and the return
statement selects the values the caller receives. Inference uses these scores to fit or sample a
posterior.
The Observe.weights field selects a finite nonnegative power of the observed
likelihood, with a scalar or one value per observation batch position. It
changes the score while retaining the raw response distribution for sampling
and pointwise likelihood extraction. The
observation-weight reference
explains validation, zero weights, and the reduction order.
programs
¶
Monadic programs: sequenced probabilistic programs as ContinuousMorphisms.
A MonadicProgram defines a ContinuousMorphism via monadic sequencing
of draw steps. Each step samples from a named morphism, optionally
conditioned on previously drawn variables, and binds the result.
The program returns one or more of the bound variables as its output.
Sequencing is Kleisli composition for the probability monad, as in
the let x ~ D in ... bindings of probabilistic programming
languages.
Features
- Single and tuple returns:
return xorreturn (x, y, z) - Named input parameters for product-domain sub-programs
- Multi-argument draw steps:
let z <- sample f(x, y) - Destructuring draws from tuple-returning sub-programs:
let (a, b) <- sample sub
Example
Given morphisms f : A -> B and g : B -> C, the monadic program::
program p : A -> C
let x <- sample f
let y <- sample g(x)
return y
is equivalent to the composition f >> g, but the program form allows fan-out (using the input in multiple draws) and non-linear variable dependency graphs.
A program can draw a tuple from another program and destructure it::
program pair : X -> R * R
let a <- sample Normal(loc=0.0, scale=1.0)
let b <- sample Normal(loc=a, scale=1.0)
return (a, b)
program main : X -> R
let (u, v) <- program pair
let s = u + v
let w <- sample Normal(loc=s, scale=1.0)
return w
ProgramEvaluator
¶
Bases: Protocol
What runs a program: the reference machine under the handler stack.
The evaluator lives in quivers.effects, which builds on programs;
it installs itself here when imported, so a program's own methods
reach it without the program package depending on the effects
package at import.
sample_program
¶
sample_program(program: MonadicProgram, x: Tensor, sample_shape: Size, observations: Mapping[str, Tensor] | None) -> Tensor | dict[str, Tensor]
Run the program forward.
| PARAMETER | DESCRIPTION |
|---|---|
program
|
The program.
TYPE:
|
x
|
Program input.
TYPE:
|
sample_shape
|
Leading sample dimensions.
TYPE:
|
observations
|
Values to clamp observed variables to, and host data.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor or dict[str, Tensor]
|
The program's return value. |
Source code in src/quivers/continuous/programs.py
log_joint
¶
log_joint(program: MonadicProgram, x: Tensor, intermediates: Mapping[str, Tensor]) -> Tensor
Score the program at values for all of its draws.
| PARAMETER | DESCRIPTION |
|---|---|
program
|
The program.
TYPE:
|
x
|
Program input.
TYPE:
|
intermediates
|
A value for every draw, and host data.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The joint log density of each run of the input, shape
|
Source code in src/quivers/continuous/programs.py
MonadicProgram
¶
MonadicProgram(domain: AnySpace, codomain: AnySpace, steps: Sequence[Step], return_vars: tuple[str, ...], params: tuple[str, ...] | None = None, return_labels: tuple[str, ...] | None = None, effect_set: frozenset[str] | None = None)
Bases: ContinuousMorphism
A probabilistic program defined by monadic sequencing of draw steps.
Each draw step samples from a ContinuousMorphism and binds the result to one or more named variables. Later steps can reference earlier bindings as their input. The program's output is the value(s) of the designated return variable(s).
| PARAMETER | DESCRIPTION |
|---|---|
domain
|
The program's input space.
TYPE:
|
codomain
|
The program's output space.
TYPE:
|
steps
|
TYPE:
|
return_vars
|
Name(s) of the bound variable(s) whose value(s) are the program output.
TYPE:
|
params
|
Named input parameters for product-domain programs. When set, the program input is split along the feature dimension and each component is pre-bound in the env.
TYPE:
|
return_labels
|
Optional labels for tuple return fields. When set, the output dict uses these labels as keys instead of the variable names. Length must match return_vars.
TYPE:
|
effect_set
|
The declared effect row (
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
input_contract |
Checked external parameters and site metadata, when compiled from QVR.
TYPE:
|
host_index_bounds |
Bounds of finite axes indexed directly by each external datum. A run refuses negative and out-of-range indices before evaluating a gather.
TYPE:
|
host_data_types |
The checked type of each host datum the program reads by name, keyed by name. The DSL compiler fills it from the program's checked elaboration; a run refuses a supplied datum whose shape or element type does not inhabit its entry. Empty for a program built directly, whose data carry no checked contract.
TYPE:
|
host_data_shared |
The host data whose checked type leads with the plate of the draw they fill; each may also be supplied without that axis, as one value every row shares.
TYPE:
|
host_data_notes |
For a host datum the program passes straight to a computation's parameter, a located note naming that call, which a refusal of the datum's shape carries. Filled by the DSL compiler.
TYPE:
|
site_plates |
The plates each draw or observe site ranges over, keyed by the
site's name: one
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a step binds no name, or two draws or observes bind the same name. |
Source code in src/quivers/continuous/programs.py
steps
property
¶
steps: tuple[Step, ...]
The program body, in order.
| RETURNS | DESCRIPTION |
|---|---|
tuple[Step, ...]
|
The records the program was built from. |
steps_list_sites
property
¶
Whether the steps list every site a run of the program reaches.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
potential_sites
property
¶
The trace names of the scores that are potentials of the prior.
| RETURNS | DESCRIPTION |
|---|---|
frozenset[str]
|
The name of every score step whose role is |
observed_names
property
¶
step_module
¶
The registered module a draw or observe step applies.
For a ContinuousMorphism
this is the morphism itself; for a backend-agnostic
Morphism it is the parameter container
as_torch_module wraps it in.
| PARAMETER | DESCRIPTION |
|---|---|
step
|
One of the program's steps. |
| RETURNS | DESCRIPTION |
|---|---|
Module
|
The submodule the program registered for the step. |
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If the program registered no module for the step. |
Source code in src/quivers/continuous/programs.py
rsample
¶
rsample(x: Tensor, sample_shape: Size = Size(), observations: dict[str, Tensor] | None = None) -> Tensor | dict[str, Tensor]
Run the program forward, returning the designated output(s).
The program runs on the reference machine under the active
handler stack, so a clamp, do, or trace in scope applies
to the draws the run makes.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
Program input. Its
TYPE:
|
sample_shape
|
Additional leading sample dimensions; each element is one independent run of the program. |
observations
|
Values to clamp observed variables to, keyed by variable name, together with any host data the steps read by name.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor or dict[str, Tensor]
|
The value of the return variable(s). Returns a tensor for single-variable returns, or a dict keyed by variable name for tuple returns. |
Source code in src/quivers/continuous/programs.py
has_conditional_density
¶
No: a program's density at its output marginalizes its draws.
log_prob
raises for exactly this reason, and a caller choosing between
constructions reads the answer here rather than by catching
that raise.
log_joint
is the exact route: it scores the draws themselves, given
values for all of them.
Source code in src/quivers/continuous/programs.py
log_prob
¶
Log-probability is not supported for monadic programs.
Computing log p(y | x) for a monadic program requires
marginalizing over all intermediate variables, which is
intractable in general. Use rsample for forward sampling
and condition via score function estimators or variational
methods.
| RAISES | DESCRIPTION |
|---|---|
NotImplementedError
|
Always. |
Source code in src/quivers/continuous/programs.py
log_joint
¶
Joint log-density given all intermediate values.
When all intermediate variables are observed (e.g. during inference with HMC/NUTS), computes the joint log-density:
log p(x_1, ..., x_n | input) = sum_i log p(x_i | pa(x_i))
where pa(x_i) is the parent variable of step i (either the
program input or a previously drawn variable). The program
runs on the reference machine with every draw conditioned on
its given value, under the active handler stack, so the joint
is the one trace reports.
An input of B rows is B independent runs of the whole
program, and the joint is one number per run; the joint of all
the runs is the sum of the result. The rows the program
observes come from its data and its plates, not from the input,
so a program whose observations live in a plate is scored on a
one-row input.
The runs are scored together, each equal to its own score up to rounding, when every step declares that it can be evaluated at many positions, none draws at random, no host datum is given per run, and no handler on the stack does more than fix sites. Otherwise they are scored one by one.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
Program input, one row per run.
TYPE:
|
intermediates
|
Values for ALL bound variables (keyed by variable name
or by return label if labels are set), together with any
host data the steps read by name. A value is given either
once per run, along a leading axis of length
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The joint log-density of each run, shape |
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If a draw the program makes is given no value. |
Source code in src/quivers/continuous/programs.py
step_key
¶
The submodule name a program registers a draw's morphism under.
| PARAMETER | DESCRIPTION |
|---|---|
step
|
A draw or observe step. |
| RETURNS | DESCRIPTION |
|---|---|
str
|
|
Source code in src/quivers/continuous/programs.py
install_evaluator
¶
install_evaluator(evaluator: ProgramEvaluator) -> None
Install the evaluator every program's methods run through.
| PARAMETER | DESCRIPTION |
|---|---|
evaluator
|
The evaluator.
TYPE:
|
Source code in src/quivers/continuous/programs.py
Cited sources¶
Eugenio Moggi. Notions of Computation and Monads. Information and Computation, 93(1):55–92, 1991. URL: https://www.sciencedirect.com/science/article/pii/0890540191900524, doi:10.1016/0890-5401(91)90052-4.
Michèle Giry. A Categorical Approach to Probability Theory. In B. Banaschewski, editor, Categorical Aspects of Topology and Analysis, volume 915 of Lecture Notes in Mathematics, pages 68–85. Springer, 1982. URL: https://link.springer.com/chapter/10.1007/BFb0092872, doi:10.1007/BFb0092872.