Program Steps¶
A MonadicProgram is built from these
records, each of which does one thing in the environment of named values
(program structure):
Draw samples a value,
Observe scores an observation,
Let computes a deterministic value,
Score adds a log weight,
Call runs a subprogram's steps in place, and
Scan runs a step program once per position of a
sequence. A score whose contribution is a sum over
units declares them in a
UnitFactorization, and an observation whose
density a score holds draws its response from a
ResponseLaw.
RunConditions says which factors a run leaves
out, and a step that holds a factor gives its function under them. The Indexed argument form indexes a
collection, and reading declares the names a step
function reads. A function given to a step declares whether it can be evaluated at
many positions at once, through the
step's batched field or mappable. The DSL compiler emits these records, so a program built from them in Python is the
one the compiler would build from the equivalent source, as the
programs guide shows.
program_steps
¶
The steps a MonadicProgram is a sequence of.
A program is built from six kinds of step, each a record of the
Step union:
Drawbinds names to a sample from a morphism, applied to the program input or to earlier bindings;Observeis a draw whose value is supplied as data and scored rather than sampled;Letbinds a name deterministically, to a constant, an alias, or a function of earlier bindings;Scorebinds a name to a function of earlier bindings whose value also joins the log joint;Callruns a sub-program's steps in place and binds what it returns;Scanruns a step program at every position of a sequence, threading a state, and binds the final state.
These are the records the DSL compiler emits, so a program assembled from them in Python is the program the compiler would build from the equivalent source.
A step function reads the environment by name. One that declares the
names it reads, through reading,
is encoded as a step over those values alone; one that declares nothing
is encoded over every value bound before it, which is correct but makes
a long program's encoding grow with its length.
READS
module-attribute
¶
The attribute a step function declares the names it reads under.
MAPPING
module-attribute
¶
The attribute a step function declares its mapping under.
StepFunction
¶
StepFunction = Callable[[Environment], Tensor]
A let or score step's function of the environment.
StepArgument
¶
StepArgument = str | Indexed
One argument of a draw or observe step: a binding's name, or an
Indexed gather of one.
Indexed
didactic-model
¶
Bases: Model
A binding gathered at index bindings, as mu[group] in source.
With mu of shape (K, ...) and an integer group of shape
(N,), the argument has shape (N, ...). Several indices
gather left to right.
| ATTRIBUTE | DESCRIPTION |
|---|---|
name |
The binding gathered from.
TYPE:
|
indices |
The integer bindings it is gathered at, at least one.
TYPE:
|
StepMapping
didactic-model
¶
StepMapping(*, obstacle: str | None = None, shared: frozenset[str] = frozenset(), draws: bool = False)
Bases: Model
Whether a step function can be mapped over many positions.
| ATTRIBUTE | DESCRIPTION |
|---|---|
obstacle |
Why it cannot be mapped, or
TYPE:
|
shared |
The names it reads whose values must be the same at every position, because what it computes is laid out by them.
TYPE:
|
draws |
Whether it draws at random, so that each position takes a draw of its own.
TYPE:
|
RunConditions
didactic-model
¶
RunConditions(*, fixed: frozenset[str] = frozenset(), subsets: dict[str, Tensor] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY))
Bases: ValueModel
What a run does to the factors of a score besides evaluating them.
| PARAMETER | DESCRIPTION |
|---|---|
fixed
|
The responses an intervention fixes. The conditional factor of a fixed response is removed from the joint; its value is read by everything after it.
TYPE:
|
subsets
|
The positions kept of each subsampled plate, by name, distinct and in increasing order.
TYPE:
|
unconditioned
property
¶
Whether the run evaluates every factor in full.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
PlateMembers
didactic-model
¶
PlateMembers(*, plate: str, extent: int, units: StepFunction = field(opaque=True, extras=OPAQUE_BY_IDENTITY), positions: StepFunction = field(opaque=True, extras=OPAQUE_BY_IDENTITY))
Bases: ValueModel
The elements of a plate that a factored score reads, and their units.
| PARAMETER | DESCRIPTION |
|---|---|
plate
|
The plate's name: the object of a response's rows, or of the grouping plate of a block inside the one that scores.
TYPE:
|
extent
|
The plate's extent.
TYPE:
|
units
|
From the environment to the unit of each element,
TYPE:
|
positions
|
From the environment to the position of each element along the
plate,
TYPE:
|
UnitRows
didactic-model
¶
UnitRows(*, response: str, units: StepFunction = field(opaque=True, extras=OPAQUE_BY_IDENTITY), one_row_per_unit: str)
Bases: ValueModel
Which unit of a factored score each row of a response belongs to.
| PARAMETER | DESCRIPTION |
|---|---|
response
|
The observed name whose rows the map sends to units.
TYPE:
|
units
|
The row map: from the environment to a long tensor of shape
TYPE:
|
one_row_per_unit
|
The change to the program that would put each row in a unit of its own, as a sentence for a refusal to state. The changed program is another model.
TYPE:
|
UnitFactorization
didactic-model
¶
UnitFactorization(*, latent: str, axes: tuple[str, ...], sizes: tuple[int, ...], weights: StepFunction = field(opaque=True, extras=OPAQUE_BY_IDENTITY), raw_weights: StepFunction = field(opaque=True, extras=OPAQUE_BY_IDENTITY), rows: tuple[UnitRows, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), density_obstacle: str | None = None, members: tuple[PlateMembers, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), under: Callable[[RunConditions], UnitFactorization] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))
Bases: ValueModel
How a score is a sum of one log weight per unit.
A score S factors over a set of units U when
S = sum_u w(u), with w(u) reading the rows that the row maps
send to u and no other row. The units of a grouped marginalize
block are the positions of its grouping plate; a block with one latent
for all its rows has one unit, and its axes are empty.
A row of a response has a log weight of its own exactly when its unit holds that row and no other row of any response. The weights of the units exist in every case.
| PARAMETER | DESCRIPTION |
|---|---|
latent
|
The name the score sums out.
TYPE:
|
axes
|
The objects whose product indexes the units, outermost first.
TYPE:
|
sizes
|
The extent of each axis.
TYPE:
|
weights
|
From the environment to the log weight of each unit, of shape
TYPE:
|
raw_weights
|
The same weights with every likelihood power of the score's
observations left out;
TYPE:
|
rows
|
The row map of each response the score reads.
TYPE:
|
density_obstacle
|
Why the weight of a unit is not the log density of its rows, or
TYPE:
|
members
|
The plates whose elements lie in the units, besides the unit axes.
TYPE:
|
under
|
The factorization in a run under conditions;
TYPE:
|
reads
property
¶
The names the factorization reads.
| RETURNS | DESCRIPTION |
|---|---|
frozenset[str] | None
|
The names the weights and the row maps read, or |
ResponseLaw
didactic-model
¶
ResponseLaw(*, marginal: Callable[[Environment], Distribution] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), draw: StepFunction = field(opaque=True, extras=OPAQUE_BY_IDENTITY), row_axis: str | None = None, under: Callable[[RunConditions], ResponseLaw] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))
Bases: ValueModel
The law of a response whose density a score step carries.
The response of a marginalize block has no density of its own in
the joint: the block's score holds it. The response still has a law
given the values the block does not sum out, and a run that is given
no value for it draws from that law.
| PARAMETER | DESCRIPTION |
|---|---|
marginal
|
From the environment to the law of each row of the response with the block's latents summed out.
TYPE:
|
draw
|
From the environment to one joint draw of all the rows. Rows that share a latent share its drawn value, and a response that follows another of the same block is drawn given that one's value.
TYPE:
|
row_axis
|
The plate of the response's rows.
TYPE:
|
under
|
The law in a run under conditions;
TYPE:
|
reads
property
¶
The names the law reads.
| RETURNS | DESCRIPTION |
|---|---|
frozenset[str] | None
|
The names its two functions read, or |
Step
didactic-model
¶
Bases: TaggedUnion, ValueModel
One step of a MonadicProgram.
The variants are Draw,
Observe,
Let,
Score,
Call, and
Scan.
Steps compare by value over their names, tags, and arguments, and by identity over the morphisms, functions, constants, and tensors they hold: two steps are equal exactly when they agree on the former and share the latter objects.
Draw
didactic-model
¶
Draw(*, names: tuple[str, ...], morphism: ContinuousMorphism | Morphism = field(opaque=True, extras=OPAQUE_BY_IDENTITY), args: tuple[StepArgument, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), kind: Literal['draw'] = 'draw')
Bases: Step
Bind names to a sample from a morphism.
In source, let x <- sample f(a, b). With no arguments the morphism
reads the program input; with one, it reads that binding; with
several, it reads their concatenation along the feature axis, each
placed by the declared parameter shape when the morphism is an
inline distribution.
| ATTRIBUTE | DESCRIPTION |
|---|---|
names |
The names bound. One name binds the sample; several destructure a tuple-returning sub-program, or split a product-codomain sample along its components.
TYPE:
|
morphism |
The kernel sampled from. A
TYPE:
|
args |
The bindings the morphism reads, or
TYPE:
|
kind |
The variant tag.
TYPE:
|
Observe
didactic-model
¶
Observe(*, names: tuple[str, ...], morphism: ContinuousMorphism | Morphism = field(opaque=True, extras=OPAQUE_BY_IDENTITY), args: tuple[StepArgument, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), weights: float | StepArgument | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), event: ObservationEvent | None = None, law: ResponseLaw | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), kind: Literal['observe'] = 'observe')
Bases: Step
Score supplied data under a morphism.
In source, observe y ~ f(a, b). The step reads its arguments as
Draw does; its value is
supplied under its name through observations when sampling and
through the intermediates when scoring, and its log density joins
the log joint. If an earlier binding already supplies the name,
the observation scores that value. It adds no latent coordinate;
a computed plated value retains the plate's row and event axes.
| ATTRIBUTE | DESCRIPTION |
|---|---|
names |
The names bound to the observed value.
TYPE:
|
morphism |
The kernel the data are scored under.
TYPE:
|
args |
The bindings the morphism reads, or
TYPE:
|
weights |
A nonnegative finite power-likelihood weight, or a binding with one weight per observation row. It changes scoring and leaves sampling and the underlying response density unchanged.
TYPE:
|
event |
Recording and truncation roles, resolved from the same environment as arguments.
TYPE:
|
law |
The law a run draws the response from when a score step carries
its density;
TYPE:
|
kind |
The variant tag.
TYPE:
|
Let
didactic-model
¶
Let(*, name: str, value: int | float | str | StepFunction = field(opaque=True, extras=OPAQUE_BY_IDENTITY), batched: bool = False, under: Callable[[RunConditions], StepFunction] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), kind: Literal['let'] = 'let')
Bases: Step
Bind a name deterministically.
In source, let w = expression.
| ATTRIBUTE | DESCRIPTION |
|---|---|
name |
The name bound.
TYPE:
|
value |
A constant, broadcast over the batch; the name of an earlier
binding, which the step aliases; or a function of the
environment, which may declare what it reads through
TYPE:
|
batched |
Whether a function
TYPE:
|
under |
The function in a run under conditions, for a binding that holds a
factor of a score;
TYPE:
|
kind |
The variant tag.
TYPE:
|
Score
didactic-model
¶
Score(*, name: str, score: StepFunction = field(opaque=True, extras=OPAQUE_BY_IDENTITY), role: Literal['potential', 'likelihood'] = 'potential', batched: bool = False, units: UnitFactorization | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), under: Callable[[RunConditions], StepFunction] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), kind: Literal['score'] = 'score')
Bases: Step
Bind a name to a log-density contribution.
The function's value is bound, as a let step's would be, and added
to the log joint. The DSL compiler emits one for a marginalize
block, whose function sums the block's scores over the
marginalized variable.
| ATTRIBUTE | DESCRIPTION |
|---|---|
name |
The name bound.
TYPE:
|
score |
The contribution, of shape
TYPE:
|
role |
Explicit potentials are retained under prior-only inference. A compiler-generated marginalized response likelihood is classified separately so the common observation policy can omit it.
TYPE:
|
batched |
Whether
TYPE:
|
units |
How the contribution is a sum of one log weight per unit, or
TYPE:
|
under |
The function in a run under conditions;
TYPE:
|
kind |
The variant tag.
TYPE:
|
reads
property
¶
The names the step reads.
| RETURNS | DESCRIPTION |
|---|---|
frozenset[str] | None
|
The names its function and its factorization read, or |
Call
didactic-model
¶
Call(*, name: str, program: ContinuousMorphism = field(opaque=True, extras=OPAQUE_BY_IDENTITY), args: tuple[str, ...] = (), kind: Literal['call'] = 'call')
Bases: Step
Bind a name to what a sub-program returns, its steps run in place.
The compiled runtime builds one for the call of a scan cell in the
cell's step program. The callee's steps run as steps of the caller:
its parameters are bound to the arguments, its sites are sites of the
caller under their own labels, and an input label it reads without
binding it is read from the step program's binding of that label,
which is the binding the scanning apply step names. Nothing the
callee binds is visible to the caller apart from the value bound to
name.
| ATTRIBUTE | DESCRIPTION |
|---|---|
name |
The name bound to the callee's return value.
TYPE:
|
program |
The callee, a
TYPE:
|
args |
The bindings passed for the callee's parameters, in order: one per declared parameter, or one for a callee without named parameters, which reads it as its input.
TYPE:
|
kind |
The variant tag.
TYPE:
|
Scan
didactic-model
¶
Scan(*, name: str, step: ContinuousMorphism = field(opaque=True, extras=OPAQUE_BY_IDENTITY), source: str | None = None, initial: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), initial_from: str | None = None, bindings: dict[str, str] = {}, outputs: Literal['last', 'all'] = 'last', reverse: bool = False, kind: Literal['scan'] = 'scan')
Bases: Step
Bind a name to the state of a step program run along a sequence.
In source, let h <- sample f >> scan(cell) with cell a program.
The step program takes one position's entry and the previous state,
(x_t, h_prev), and returns the next state; the scan runs it at
every position of the sequence, left to right (or right to left,
for a reversed scan), from the initial state, and binds the last
state, or every state for outputs="all". The step program's
steps are steps of the enclosing program, reached once per position
visited: the n-th time a run reaches a site labelled s it is
the site "s@n",
which a trace records and an observation, a clamp, or a joint
density addresses. A name the step program reads without binding
it is one of its input labels, and bindings names the enclosing
program's binding or host data it reads; the step program sees no
other name of the enclosing program.
| ATTRIBUTE | DESCRIPTION |
|---|---|
name |
The name bound to the final state.
TYPE:
|
step |
The step program, a
TYPE:
|
source |
The binding holding the sequence, or
TYPE:
|
initial |
The initial state, of shape
TYPE:
|
initial_from |
A binding of the enclosing program, made before the scan, whose
value is the initial state (
TYPE:
|
bindings |
Each input label the step program reads, mapped to the name of the enclosing program's binding (or host data) it reads there.
TYPE:
|
outputs |
TYPE:
|
reverse |
Whether the scan visits the positions from the last to the
first. Its sites are numbered in the order it visits them, so
TYPE:
|
kind |
The variant tag.
TYPE:
|
reading
¶
Declare the environment names a step callable reads.
| PARAMETER | DESCRIPTION |
|---|---|
function
|
The callable, a let or score step's value.
TYPE:
|
names
|
The names it reads from the environment it is called with.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
StepCallable
|
The same callable, carrying the names under |
Source code in src/quivers/continuous/program_steps.py
reads_of
¶
The environment names a step callable declares it reads.
| PARAMETER | DESCRIPTION |
|---|---|
function
|
A let or score step's value.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
frozenset[str] | None
|
The declared names, or |
Source code in src/quivers/continuous/program_steps.py
mappable
¶
mappable(function: StepCallable, obstacle: str | None = None, shared: Iterable[str] = (), draws: bool = False) -> StepCallable
Declare whether a step callable can be mapped over many positions.
A mappable callable computes its value with tensor operations alone:
it branches on no value, and reads the shapes of one run. It is then
evaluated at many positions by torch.func.vmap,
with no batch axis for it to handle. The DSL compiler declares it of
the functions it builds. A callable written for an explicit batch
axis declares batched=True on its step instead.
| PARAMETER | DESCRIPTION |
|---|---|
function
|
The callable, a let or score step's value.
TYPE:
|
obstacle
|
Why it cannot be mapped, or
TYPE:
|
shared
|
The names it reads whose values must be the same at every position: the number of entries it computes depends on them.
TYPE:
|
draws
|
Whether it draws at random.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
StepCallable
|
The same callable, carrying the declaration. |
Source code in src/quivers/continuous/program_steps.py
mapping_of
¶
mapping_of(function: Callable[..., object]) -> StepMapping
The mapping a step callable declares.
| PARAMETER | DESCRIPTION |
|---|---|
function
|
A let or score step's value.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
StepMapping
|
The declaration; for a callable that makes none, an obstacle. |