Skip to content

Composite lets

These helpers normalize a program AST before lowering. They rewrite supported composite expressions into the forms the next stage expects, which makes their dependencies explicit (one checked core) without asking later stages to handle every source spelling.

Internal module

This module is an implementation detail of the compiler and its tooling. Its __all__ is empty, so none of the names below are part of the public API, and they may change without notice.

composite_lets

Normalize program ASTs before IR lowering.

The pass expands sampled composite bindings into atomic sample and let steps. It preserves marginalize blocks for the lowering stage while expanding composite references inside their scopes.

LEARNED_SCAN_INIT_SUFFIX module-attribute

LEARNED_SCAN_INIT_SUFFIX = '_scan_init'

The suffix of the input a scan with init=learned starts from.

POSITIONS_BUNDLE module-attribute

POSITIONS_BUNDLE = '$positions'

The let function pairing sequences position by position.

$positions(a, b) over sequences of one length is the sequence whose entry at each position lays the entries of a and b there end to end. The expansion of a fan or @ whose branches each return every state of a scan binds it; the $ keeps it apart from every function a source can call.

ModelBindError

ModelBindError(step: SampleStep, expected: str)

Bases: StepResolutionError

A model bind names a term outside its operation's namespace.

Source code in src/quivers/dsl/composite_lets.py
def __init__(self, step: SampleStep, expected: str) -> None:
    self.step = step
    super().__init__(
        "qvr-expand",
        ["program:model-bind"],
        explanation=(f"{step.morphism!r} requires `<- {expected}` in this scope"),
    )

ScanBinding didactic-model

ScanBinding(*, label: str, name: str)

Bases: Model

An input label of a scan and the scanning program's name bound to it.

PARAMETER DESCRIPTION
label

The label: a free data name the scan's cell reads.

TYPE: str

name

The scanning program's name the apply step binds it to, resolved in the program's scope where the step is written.

TYPE: str

ScanCall didactic-model

ScanCall(*, step: str, sequence: str, init: str | None = None, init_label: str | None = None, bindings: tuple[ScanBinding, ...] = (), outputs: Literal['last', 'all'] = 'last', reverse: bool = False, marginal: bool = False)

Bases: Model

A scan as the expansion binds it: let h = scan(step, xs, ...).

PARAMETER DESCRIPTION
step

The step program's name.

TYPE: str

sequence

The name of the sequence the scan runs over.

TYPE: str

init

The initial state's name: the scanning program's name an apply step binds the scan's init= label to, or the <cell>_scan_init input of a learned initial state; None to start from zero.

TYPE: str | None DEFAULT: None

init_label

The label the scan's init= gives its initial state, when the apply step binds it; None otherwise.

TYPE: str | None DEFAULT: None

bindings

Every binding of the apply step the scan comes from. The scan reads its cell's free data names through these, never through the spelling of the scanning program's own names.

TYPE: tuple[ScanBinding, ...] DEFAULT: ()

outputs

Whether the scan's value is its final state or every state.

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

reverse

Whether the scan visits the positions from the last to the first.

TYPE: bool DEFAULT: False

marginal

Whether the scan sums out a finite state its cell marginalizes and returns (a marginalized chain); step then names the cell itself and init the distribution of the state before the first position.

TYPE: bool DEFAULT: False

bound

bound(label: str) -> str | None

The scanning program's name bound to an input label.

PARAMETER DESCRIPTION
label

The label.

TYPE: str

RETURNS DESCRIPTION
str | None

The bound name, or None when the apply step binds no such label.

Source code in src/quivers/dsl/composite_lets.py
def bound(self, label: str) -> str | None:
    """The scanning program's name bound to an input label.

    Parameters
    ----------
    label : str
        The label.

    Returns
    -------
    str | None
        The bound name, or ``None`` when the apply step binds no such
        label.
    """
    return next(
        (binding.name for binding in self.bindings if binding.label == label),
        None,
    )

validate_model_binds

validate_model_binds(module: Module) -> None

Check each explicit model operation against its source namespace.

Source code in src/quivers/dsl/composite_lets.py
def validate_model_binds(module: Module) -> None:
    """Check each explicit model operation against its source namespace."""
    morphisms, lets, programs = _model_tables(module)
    for declaration in programs.values():
        program = _Program(morphisms, lets, programs, (), ())
        _validate_draw_operations(
            declaration.draws,
            program,
            _morphism_formals(declaration),
        )

expand_composite_lets

expand_composite_lets(module: Module, *, target: str | None = None) -> Module

Rewrite program_decl bodies so composite-let sample steps become equivalent chains of atomic sample steps.

A composite let is a DefineDecl whose .expr is an ExprCompose (the prior >> likelihood form). Each SampleStep / ObserveStep whose morphism slot names such a let is rewritten into a sequence of fresh SampleSteps, one per element of the composition chain, with the trailing step keeping the original step's bound variable name.

The returned Module shares vertex identity with the input for every non-rewritten statement; only the program_decls with composite-let references are rebuilt.

The rewrite is target-independent: every backend consumes the same expanded AST, and the choice of whether to enumerate or to sample a marginalize latent is each renderer's, taken against the lowered IRMarginalize. target is accepted so callers can name the backend they are compiling for without the pass branching on it.

Source code in src/quivers/dsl/composite_lets.py
def expand_composite_lets(
    module: Module,
    *,
    target: str | None = None,
) -> Module:
    """Rewrite `program_decl` bodies so composite-let sample steps
    become equivalent chains of atomic sample steps.

    A composite let is a `DefineDecl` whose `.expr` is an `ExprCompose`
    (the `prior >> likelihood` form). Each `SampleStep` /
    `ObserveStep` whose `morphism` slot names such a let is rewritten
    into a sequence of fresh `SampleStep`s, one per element of the
    composition chain, with the trailing step keeping the original
    step's bound variable name.

    The returned `Module` shares vertex identity with the input for
    every non-rewritten statement; only the `program_decl`s with
    composite-let references are rebuilt.

    The rewrite is target-independent: every backend consumes the same
    expanded AST, and the choice of whether to enumerate or to sample a
    marginalize latent is each renderer's, taken against the lowered
    [`IRMarginalize`][quivers.transpile.ir.IRMarginalize]. `target` is
    accepted so callers can name the backend they are compiling for
    without the pass branching on it.
    """
    validate_model_binds(module)
    morphism_table, let_table, program_table = _model_tables(module)

    del target
    declared = set(morphism_table)
    declared_programs = set(program_table)
    new_statements: list = []
    for stmt in module.statements:
        if isinstance(stmt, ProgramDecl):
            program = _Program(
                morphism_table,
                let_table,
                program_table,
                _domain_names(stmt),
                _domain_factors(stmt.domain),
            )
            morphism_formals = _morphism_formals(stmt)
            refuse_program_cell_calls(stmt.draws, program_table, morphism_formals)
            new_draws = _expand_draws(stmt.draws, program, morphism_formals)
            refuse_marginal_chain_reads(tuple(new_draws), stmt.return_vars)
            # A scan's step program is declared before the program that
            # scans with it, so a consumer reading in order sees it.
            for name, declaration in program.programs.items():
                if name not in declared_programs:
                    declared_programs.add(name)
                    new_statements.append(declaration)
            if new_draws is stmt.draws:
                new_statements.append(stmt)
            else:
                new_statements.append(stmt.with_(draws=tuple(new_draws)))
        else:
            new_statements.append(stmt)
    # A replica of a `[replicate=k]` morphism and a copy a `stack`
    # makes are morphisms of their own, with their own parameters;
    # the expanded module declares them so every consumer sees them.
    synthesized = [
        decl for name, decl in morphism_table.items() if name not in declared
    ]
    if synthesized:
        last = max(
            index
            for index, stmt in enumerate(new_statements)
            if isinstance(stmt, MorphismDecl)
        )
        new_statements[last + 1 : last + 1] = synthesized
    return module.with_(statements=tuple(new_statements))

expand_program_scans

expand_program_scans(declaration: ProgramDecl, module: Module) -> tuple[tuple[ProgramStep, ...], dict[str, ProgramDecl]]

Expand the draws of one program that run a scan.

A static application or an observation whose morphism resolves to a chain with a scan is rewritten exactly as expand_composite_lets rewrites it: a let h = scan(step, xs) over a step program, with the chain's other elements as steps of the step program or of the program. Every other step is kept as written. The expansion draws its fresh names from the serial the module-wide expansion uses, so an expanded step binds the names the checked elaboration binds.

PARAMETER DESCRIPTION
declaration

The program.

TYPE: ProgramDecl

module

The module declaring it, its morphisms, defines, and programs.

TYPE: Module

RETURNS DESCRIPTION
tuple[tuple[ProgramStep, ...], dict[str, ProgramDecl]]

The program's draws, the input itself when no step runs a scan; and the step programs the expansion declared, by name, each after the step programs it scans with.

Source code in src/quivers/dsl/composite_lets.py
def expand_program_scans(
    declaration: ProgramDecl, module: Module
) -> tuple[tuple[ProgramStep, ...], dict[str, ProgramDecl]]:
    """Expand the draws of one program that run a scan.

    A static application or an observation whose morphism resolves to a chain
    with a ``scan`` is rewritten exactly as
    [`expand_composite_lets`][quivers.dsl.composite_lets.expand_composite_lets]
    rewrites it: a ``let h = scan(step, xs)`` over a step program, with
    the chain's other elements as steps of the step program or of the
    program. Every other step is kept as written. The expansion draws
    its fresh names from the serial the module-wide expansion uses, so
    an expanded step binds the names the checked elaboration binds.

    Parameters
    ----------
    declaration : ProgramDecl
        The program.
    module : Module
        The module declaring it, its morphisms, defines, and programs.

    Returns
    -------
    tuple[tuple[ProgramStep, ...], dict[str, ProgramDecl]]
        The program's draws, the input itself when no step runs a scan;
        and the step programs the expansion declared, by
        name, each after the step programs it scans with.
    """
    morphisms, lets, programs = _model_tables(module)
    declared = set(programs)
    morphism_formals = _morphism_formals(declaration)
    refuse_program_cell_calls(declaration.draws, programs, morphism_formals)
    if not _selects(declaration.draws, morphisms, lets, morphism_formals, _scans):
        return declaration.draws, {}
    program = _Program(
        morphisms,
        lets,
        programs,
        _domain_names(declaration),
        _domain_factors(declaration.domain),
    )
    draws = _expand_draws(
        declaration.draws,
        program,
        morphism_formals,
        select=_scans,
    )
    refuse_marginal_chain_reads(draws, declaration.return_vars)
    steps = {
        name: decl for name, decl in program.programs.items() if name not in declared
    }
    return draws, steps

refuse_marginal_chain_reads

refuse_marginal_chain_reads(draws: tuple[ProgramStep, ...], returned: tuple[str, ...]) -> None

Refuse a read of the name a marginalized chain binds.

The chain sums its states out, so the name its sample step binds holds no state: no later step reads it and the program does not return it. A marginalized chain inside a marginalize block is refused too, since the block's weight is a single number per atom.

PARAMETER DESCRIPTION
draws

A program's expanded steps.

TYPE: tuple[ProgramStep, ...]

returned

The names it returns.

TYPE: tuple[str, ...]

RAISES DESCRIPTION
StepResolutionError

If a later step or the return reads such a name, or such a chain lies inside a marginalize block.

Source code in src/quivers/dsl/composite_lets.py
def refuse_marginal_chain_reads(
    draws: tuple[ProgramStep, ...], returned: tuple[str, ...]
) -> None:
    """Refuse a read of the name a marginalized chain binds.

    The chain sums its states out, so the name its ``sample`` step binds
    holds no state: no later step reads it and the program does not
    return it. A marginalized chain inside a ``marginalize`` block is
    refused too, since the block's weight is a single number per atom.

    Parameters
    ----------
    draws : tuple[ProgramStep, ...]
        A program's expanded steps.
    returned : tuple[str, ...]
        The names it returns.

    Raises
    ------
    StepResolutionError
        If a later step or the return reads such a name, or such a
        chain lies inside a ``marginalize`` block.
    """
    for index, step in enumerate(draws):
        if isinstance(step, MarginalizeStep):
            for inner in step.scope:
                scan = (
                    scan_let_call(inner.value) if isinstance(inner, LetStep) else None
                )
                if scan is not None and scan.marginal:
                    raise StepResolutionError(
                        "qvr-expand",
                        [f"scan:marginal:scope:{scan.step}"],
                        explanation=(
                            f"the marginalized chain over {scan.step!r} at line "
                            f"{inner.line} lies inside the block over "
                            f"{step.var!r}; draw it in the program's body"
                        ),
                    )
            continue
        if not isinstance(step, LetStep):
            continue
        scan = scan_let_call(step.value)
        if scan is None or not scan.marginal:
            continue
        readers = [
            later
            for later in draws[index + 1 :]
            if step.name in _step_value_names(later)
        ]
        if readers or step.name in returned:
            where = f"line {readers[0].line}" if readers else "the program's return"
            raise StepResolutionError(
                "qvr-expand",
                [f"scan:marginal:read:{step.name}"],
                explanation=(
                    f"{step.name!r} binds the marginalized chain over "
                    f"{scan.step!r}, whose states are summed out, so it holds "
                    f"no state for {where} to read; the chain contributes its "
                    f"log marginal likelihood to the joint"
                ),
            )

refuse_program_cell_calls

refuse_program_cell_calls(draws: tuple[ProgramStep, ...], programs: dict[str, ProgramDecl], morphism_formals: frozenset[str] = frozenset()) -> None

Refuse every draw or call of a cell that returns a marginalized latent.

PARAMETER DESCRIPTION
draws

A program body, searched through marginalization scopes.

TYPE: tuple[ProgramStep, ...]

programs

The module's programs by name.

TYPE: dict[str, ProgramDecl]

morphism_formals

Lexical morphism formals that still await substitution.

TYPE: frozenset[str] DEFAULT: frozenset()

RAISES DESCRIPTION
StepResolutionError

If a step draws from or calls such a cell other than as the cell of a scan.

Source code in src/quivers/dsl/composite_lets.py
def refuse_program_cell_calls(
    draws: tuple[ProgramStep, ...],
    programs: dict[str, ProgramDecl],
    morphism_formals: frozenset[str] = frozenset(),
) -> None:
    """Refuse every draw or call of a cell that returns a marginalized latent.

    Parameters
    ----------
    draws : tuple[ProgramStep, ...]
        A program body, searched through marginalization scopes.
    programs : dict[str, ProgramDecl]
        The module's programs by name.
    morphism_formals : frozenset[str]
        Lexical morphism formals that still await substitution.

    Raises
    ------
    StepResolutionError
        If a step draws from or calls such a cell other than as the cell
        of a scan.
    """
    for step in draws:
        if isinstance(step, MarginalizeStep):
            refuse_program_cell_calls(step.scope, programs, morphism_formals)
        elif not (
            isinstance(step, (SampleStep, ObserveStep))
            and not step.morphism_is_module_bound
            and step.morphism in morphism_formals
        ):
            _refuse_cell_use(step, programs)

refuse_standalone_cell

refuse_standalone_cell(cell: ProgramDecl, line: int) -> None

Refuse a concrete call of a program that only runs as a scan cell.

Source code in src/quivers/dsl/composite_lets.py
def refuse_standalone_cell(cell: ProgramDecl, line: int) -> None:
    """Refuse a concrete call of a program that only runs as a scan cell."""
    if returns_marginalized_latent(cell):
        raise StepResolutionError(
            "qvr-expand",
            [f"scan:marginal:entry:{cell.name}"],
            explanation=(
                f"the step at line {line} runs {cell.name!r}, which returns "
                f"the latent it marginalizes and so has no value of its own; it "
                f"runs only as the cell of `scan({cell.name}, init=p)`"
            ),
        )

is_learned_scan_init

is_learned_scan_init(name: str) -> bool

Whether a scan's initial-state name is a learned initial state.

PARAMETER DESCRIPTION
name

The third argument of scan(step, xs, init).

TYPE: str

RETURNS DESCRIPTION
bool

True for the <cell>_scan_init input init=learned introduces; false for a binding of the scanning program.

Source code in src/quivers/dsl/composite_lets.py
def is_learned_scan_init(name: str) -> bool:
    """Whether a scan's initial-state name is a learned initial state.

    Parameters
    ----------
    name : str
        The third argument of ``scan(step, xs, init)``.

    Returns
    -------
    bool
        True for the ``<cell>_scan_init`` input ``init=learned``
        introduces; false for a binding of the scanning program.
    """
    return name.endswith(LEARNED_SCAN_INIT_SUFFIX)

scan_let_expression

scan_let_expression(call: ScanCall) -> LetExprCall

The let expression binding a scan.

PARAMETER DESCRIPTION
call

The scan.

TYPE: ScanCall

RETURNS DESCRIPTION
LetExprCall

scan(step, xs), with the initial state's name as a third argument when there is one, then the string flags "outputs=all", "reverse", and "marginal" for the options that differ from their defaults, then for each binding the string "$bind:<label>" followed by the bound name, and "$init:<label>" for the init= label. Every argument is positional, so the bound names are read like any other variable of the expression.

Source code in src/quivers/dsl/composite_lets.py
def scan_let_expression(call: ScanCall) -> LetExprCall:
    """The let expression binding a scan.

    Parameters
    ----------
    call : ScanCall
        The scan.

    Returns
    -------
    LetExprCall
        ``scan(step, xs)``, with the initial state's name as a third
        argument when there is one, then the string flags
        ``"outputs=all"``, ``"reverse"``, and ``"marginal"`` for the
        options that differ from their defaults, then for each binding
        the string ``"$bind:<label>"`` followed by the bound name, and
        ``"$init:<label>"`` for the ``init=`` label. Every argument is
        positional, so the bound names are read like any other variable
        of the expression.
    """
    arguments: list[LetExprNode] = [
        LetExprVar(name=call.step),
        LetExprVar(name=call.sequence),
    ]
    if call.init is not None:
        arguments.append(LetExprVar(name=call.init))
    if call.outputs == "all":
        arguments.append(LetExprString(value=_SCAN_ALL_FLAG))
    if call.reverse:
        arguments.append(LetExprString(value=_SCAN_REVERSE_FLAG))
    if call.marginal:
        arguments.append(LetExprString(value=_SCAN_MARGINAL_FLAG))
    for binding in call.bindings:
        arguments.append(LetExprString(value=f"{_SCAN_BINDING_MARK}{binding.label}"))
        arguments.append(LetExprVar(name=binding.name))
    if call.init_label is not None:
        arguments.append(LetExprString(value=f"{_SCAN_INIT_MARK}{call.init_label}"))
    return LetExprCall(func="scan", args=tuple(arguments))

scan_let_call

scan_let_call(expr: LetExprNode) -> ScanCall | None

Read a scan off a let expression scan_let_expression built.

PARAMETER DESCRIPTION
expr

The expression.

TYPE: LetExprNode

RETURNS DESCRIPTION
ScanCall | None

The scan; None when the expression is not a scan of names.

Source code in src/quivers/dsl/composite_lets.py
def scan_let_call(expr: LetExprNode) -> ScanCall | None:
    """Read a scan off a let expression `scan_let_expression` built.

    Parameters
    ----------
    expr : LetExprNode
        The expression.

    Returns
    -------
    ScanCall | None
        The scan; ``None`` when the expression is not a scan of names.
    """
    if not isinstance(expr, LetExprCall) or expr.func != "scan" or expr.arg_names:
        return None
    arguments = list(expr.args)
    variables: list[str] = []
    while arguments:
        leading = arguments[0]
        if not isinstance(leading, LetExprVar):
            break
        variables.append(leading.name)
        arguments.pop(0)
    flags: list[str] = []
    bindings: list[ScanBinding] = []
    init_label: str | None = None
    while arguments:
        argument = arguments.pop(0)
        if not isinstance(argument, LetExprString):
            return None
        value = argument.value
        if value.startswith(_SCAN_BINDING_MARK):
            bound = arguments.pop(0) if arguments else None
            if not isinstance(bound, LetExprVar):
                return None
            bindings.append(
                ScanBinding(label=value[len(_SCAN_BINDING_MARK) :], name=bound.name)
            )
        elif value.startswith(_SCAN_INIT_MARK):
            init_label = value[len(_SCAN_INIT_MARK) :]
        elif value in _SCAN_FLAGS and not bindings and init_label is None:
            flags.append(value)
        else:
            return None
    if len(variables) not in (2, 3) or len(set(flags)) != len(flags):
        return None
    return ScanCall(
        step=variables[0],
        sequence=variables[1],
        init=variables[2] if len(variables) == 3 else None,
        init_label=init_label,
        bindings=tuple(bindings),
        outputs="all" if _SCAN_ALL_FLAG in flags else "last",
        reverse=_SCAN_REVERSE_FLAG in flags,
        marginal=_SCAN_MARGINAL_FLAG in flags,
    )

positions_let_call

positions_let_call(expr: LetExprNode) -> tuple[str, ...] | None

Read $positions(a, b, ...) off a let expression.

PARAMETER DESCRIPTION
expr

The expression.

TYPE: LetExprNode

RETURNS DESCRIPTION
tuple[str, ...] | None

The paired sequences' names, in order; None when the expression is not such a call of names.

Source code in src/quivers/dsl/composite_lets.py
def positions_let_call(expr: LetExprNode) -> tuple[str, ...] | None:
    """Read ``$positions(a, b, ...)`` off a let expression.

    Parameters
    ----------
    expr : LetExprNode
        The expression.

    Returns
    -------
    tuple[str, ...] | None
        The paired sequences' names, in order; ``None`` when the
        expression is not such a call of names.
    """
    if (
        not isinstance(expr, LetExprCall)
        or expr.arg_names
        or expr.func != POSITIONS_BUNDLE
    ):
        return None
    if not expr.args or not all(isinstance(a, LetExprVar) for a in expr.args):
        return None
    return tuple(a.name for a in expr.args if isinstance(a, LetExprVar))