Skip to content

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:

  • Draw binds names to a sample from a morphism, applied to the program input or to earlier bindings;
  • Observe is a draw whose value is supplied as data and scored rather than sampled;
  • Let binds a name deterministically, to a constant, an alias, or a function of earlier bindings;
  • Score binds a name to a function of earlier bindings whose value also joins the log joint;
  • Call runs a sub-program's steps in place and binds what it returns;
  • Scan runs 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

READS = 'reads'

The attribute a step function declares the names it reads under.

MAPPING module-attribute

MAPPING = 'mapping'

The attribute a step function declares its mapping under.

Environment

Environment = dict[str, Tensor]

The bindings a step function reads, by name.

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

Indexed(*, name: str, indices: tuple[str, ...] = field(converter=_check_indices))

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: str

indices

The integer bindings it is gathered at, at least one.

TYPE: tuple[str, ...]

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 None when it can.

TYPE: str | None

shared

The names it reads whose values must be the same at every position, because what it computes is laid out by them.

TYPE: frozenset[str]

draws

Whether it draws at random, so that each position takes a draw of its own.

TYPE: bool

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: frozenset[str] DEFAULT: frozenset()

subsets

The positions kept of each subsampled plate, by name, distinct and in increasing order.

TYPE: dict[str, Tensor] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY)

unconditioned property

unconditioned: bool

Whether the run evaluates every factor in full.

RETURNS DESCRIPTION
bool

True when no response is fixed and no plate subsampled.

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: str

extent

The plate's extent.

TYPE: int

units

From the environment to the unit of each element, (elements,).

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

positions

From the environment to the position of each element along the plate, (elements,).

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

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: str

units

The row map: from the environment to a long tensor of shape (rows,) holding each row's unit, counted row-major over the unit axes. It declares what it reads through reading.

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

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: str

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: str

axes

The objects whose product indexes the units, outermost first.

TYPE: tuple[str, ...]

sizes

The extent of each axis.

TYPE: tuple[int, ...]

weights

From the environment to the log weight of each unit, of shape (prod(sizes),), row-major over the axes. Their sum is the score's contribution.

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

raw_weights

The same weights with every likelihood power of the score's observations left out; weights itself when there is none.

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

rows

The row map of each response the score reads.

TYPE: tuple[UnitRows, ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

density_obstacle

Why the weight of a unit is not the log density of its rows, or None when it is.

TYPE: str | None DEFAULT: None

members

The plates whose elements lie in the units, besides the unit axes.

TYPE: tuple[PlateMembers, ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

under

The factorization in a run under conditions; None for a score that no condition changes.

TYPE: Callable[[RunConditions], UnitFactorization] or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

reads property

reads: frozenset[str] | None

The names the factorization reads.

RETURNS DESCRIPTION
frozenset[str] | None

The names the weights and the row maps read, or None when one of them declares none and may read any bound value.

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: Callable[[Environment], Distribution] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

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: StepFunction DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

row_axis

The plate of the response's rows.

TYPE: str or None DEFAULT: None

under

The law in a run under conditions; None for a law that no condition changes.

TYPE: Callable[[RunConditions], ResponseLaw] or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

reads property

reads: frozenset[str] | None

The names the law reads.

RETURNS DESCRIPTION
frozenset[str] | None

The names its two functions read, or None when one of them declares none and may read any bound value.

Step didactic-model

Step()

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: tuple[str, ...]

morphism

The kernel sampled from. A Morphism is applied as a deterministic step through its tensor.

TYPE: ContinuousMorphism | Morphism

args

The bindings the morphism reads, or None for the program input.

TYPE: tuple[StepArgument, ...] | None

kind

The variant tag.

TYPE: Literal['draw']

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: tuple[str, ...]

morphism

The kernel the data are scored under.

TYPE: ContinuousMorphism | Morphism

args

The bindings the morphism reads, or None for the program input.

TYPE: tuple[StepArgument, ...] | None

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: float | StepArgument | None

event

Recording and truncation roles, resolved from the same environment as arguments.

TYPE: ObservationEvent or None

law

The law a run draws the response from when a score step carries its density; None for an observation that draws from its morphism at its arguments.

TYPE: ResponseLaw or None

kind

The variant tag.

TYPE: Literal['observe']

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: str

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 reading.

TYPE: float | str | StepFunction

batched

Whether a function value accepts a leading batch axis. Over many positions it is then called once, with a batch axis of length B leading every value it reads that depends on the position, ahead of the axes the value has in one run, and a value every position shares at its own shape; its result leads with that axis too. A function that declares neither this nor mappable makes the program unbatchable.

TYPE: bool

under

The function in a run under conditions, for a binding that holds a factor of a score; None for one that no condition changes. It reads no name the function of value does not read.

TYPE: Callable[[RunConditions], StepFunction] or None

kind

The variant tag.

TYPE: Literal['let']

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: str

score

The contribution, of shape (batch,).

TYPE: StepFunction

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: {'potential', 'likelihood'}

batched

Whether score accepts a leading batch axis, as Let.batched declares it of a let step's function. Over B positions the contribution then has shape (B, ...), and each row's trailing entries are summed as one run's are.

TYPE: bool

units

How the contribution is a sum of one log weight per unit, or None for a score that declares no factorization.

TYPE: UnitFactorization or None

under

The function in a run under conditions; None for a score that no condition changes. It reads no name the step does not read.

TYPE: Callable[[RunConditions], StepFunction] or None

kind

The variant tag.

TYPE: Literal['score']

reads property

reads: frozenset[str] | None

The names the step reads.

RETURNS DESCRIPTION
frozenset[str] | None

The names its function and its factorization read, or None when one of them declares none and may read any bound value.

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: str

program

The callee, a MonadicProgram with a single return variable.

TYPE: ContinuousMorphism

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: tuple[str, ...]

kind

The variant tag.

TYPE: Literal['call']

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: str

step

The step program, a MonadicProgram with two parameters, the entry and the previous state, over A * H -> H.

TYPE: ContinuousMorphism

source

The binding holding the sequence, or None for the program input. A discrete entry's sequence is (batch, seq_len); a continuous entry's is (batch, seq_len, dim) or the folded (batch, seq_len * dim).

TYPE: str | None

initial

The initial state, of shape (dim H,) and shared by every row, or None to start from zero. A learned initial state is an nn.Parameter, which the enclosing program registers.

TYPE: Tensor | None

initial_from

A binding of the enclosing program, made before the scan, whose value is the initial state (scan(cell, init=h0)), or None. A scalar binding is the one entry of a one-wide state. At most one of initial and initial_from is set.

TYPE: str | None

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: dict[str, str]

outputs

"last" binds the state after the last position visited; "all" binds the state after every position, (batch, seq_len, dim H) in input order.

TYPE: Literal['last', 'all']

reverse

Whether the scan visits the positions from the last to the first. Its sites are numbered in the order it visits them, so "s@0" is the site at the last position; a sequence of values given under "s" is still read in input order.

TYPE: bool

kind

The variant tag.

TYPE: Literal['scan']

reading

reading(function: StepCallable, names: Iterable[str]) -> StepCallable

Declare the environment names a step callable reads.

PARAMETER DESCRIPTION
function

The callable, a let or score step's value.

TYPE: StepCallable

names

The names it reads from the environment it is called with.

TYPE: Iterable[str]

RETURNS DESCRIPTION
StepCallable

The same callable, carrying the names under reads.

Source code in src/quivers/continuous/program_steps.py
def reading(
    function: StepCallable, names: collections.abc.Iterable[str]
) -> StepCallable:
    """Declare the environment names a step callable reads.

    Parameters
    ----------
    function : StepCallable
        The callable, a let or score step's value.
    names : Iterable[str]
        The names it reads from the environment it is called with.

    Returns
    -------
    StepCallable
        The same callable, carrying the names under ``reads``.
    """
    setattr(function, READS, frozenset(names))
    return function

reads_of

reads_of(function: Callable[..., object]) -> frozenset[str] | None

The environment names a step callable declares it reads.

PARAMETER DESCRIPTION
function

A let or score step's value.

TYPE: Callable

RETURNS DESCRIPTION
frozenset[str] | None

The declared names, or None when the callable declares none and may read any bound value.

Source code in src/quivers/continuous/program_steps.py
def reads_of(function: collections.abc.Callable[..., object]) -> frozenset[str] | None:
    """The environment names a step callable declares it reads.

    Parameters
    ----------
    function : Callable
        A let or score step's value.

    Returns
    -------
    frozenset[str] | None
        The declared names, or ``None`` when the callable declares none
        and may read any bound value.
    """
    names = getattr(function, READS, None)
    if names is None:
        return None
    assert isinstance(names, frozenset)
    return names

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: StepCallable

obstacle

Why it cannot be mapped, or None when it can.

TYPE: str | None DEFAULT: None

shared

The names it reads whose values must be the same at every position: the number of entries it computes depends on them.

TYPE: Iterable[str] DEFAULT: ()

draws

Whether it draws at random.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
StepCallable

The same callable, carrying the declaration.

Source code in src/quivers/continuous/program_steps.py
def mappable(
    function: StepCallable,
    obstacle: str | None = None,
    shared: collections.abc.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`][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.

    Parameters
    ----------
    function : StepCallable
        The callable, a let or score step's value.
    obstacle : str | None
        Why it cannot be mapped, or ``None`` when it can.
    shared : Iterable[str]
        The names it reads whose values must be the same at every
        position: the number of entries it computes depends on them.
    draws : bool
        Whether it draws at random.

    Returns
    -------
    StepCallable
        The same callable, carrying the declaration.
    """
    setattr(
        function,
        MAPPING,
        StepMapping(obstacle=obstacle, shared=frozenset(shared), draws=draws),
    )
    return function

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: Callable

RETURNS DESCRIPTION
StepMapping

The declaration; for a callable that makes none, an obstacle.

Source code in src/quivers/continuous/program_steps.py
def mapping_of(function: collections.abc.Callable[..., object]) -> StepMapping:
    """The mapping a step callable declares.

    Parameters
    ----------
    function : Callable
        A let or score step's value.

    Returns
    -------
    StepMapping
        The declaration; for a callable that makes none, an obstacle.
    """
    declared = getattr(function, MAPPING, None)
    if declared is None:
        return StepMapping(
            obstacle="its callable is opaque and the step does not declare batched=True"
        )
    assert isinstance(declared, StepMapping)
    return declared