Skip to content

Batched evaluation

PotentialFn.log_density_batch scores a program at many positions in one pass. Whether each step can be evaluated this way is declared, by the step for a Python callable and by the morphism for a distribution. batching_obstacles lists the steps of a program that declare nothing, or whose terms would differ between positions, and UnbatchableProgramError carries them.

batching

Which programs can be scored at many positions in one pass.

A program's log joint is evaluated at B positions by running its steps once, on values that carry the position axis (quivers._positions). Whether a step can run this way is declared, by the step for a Python callable the program cannot inspect and by the morphism for a distribution, and is never found out by running it. batching_obstacles reads the declarations of a program and of the programs it calls and scans, and the batch methods of PotentialFn raise UnbatchableProgramError when any of them stands in the way.

PositionLayoutError

Bases: ValueError

A value of a batched callable does not lead with the position axis.

A callable declared batched keeps the position axis leading every value that depends on the position. A result that does not, or a validator that refuses a value whose leading axis is not the position axis, cannot be read per position.

BatchingObstacle didactic-model

BatchingObstacle(*, step: str, reason: str)

Bases: ValueModel

A step that cannot be evaluated at many positions, and why.

ATTRIBUTE DESCRIPTION
step

The step: its kind and the names it binds.

TYPE: str

reason

Why it cannot.

TYPE: str

UnbatchableProgramError

UnbatchableProgramError(obstacles: tuple[BatchingObstacle, ...])

Bases: ValueError

A program that cannot be scored at many positions in one pass.

PARAMETER DESCRIPTION
obstacles

The steps standing in the way, in program order, and why each does.

TYPE: tuple[BatchingObstacle, ...]

ATTRIBUTE DESCRIPTION
obstacles

The same.

TYPE: tuple[BatchingObstacle, ...]

Source code in src/quivers/effects/batching.py
def __init__(self, obstacles: tuple[BatchingObstacle, ...]) -> None:
    self.obstacles = obstacles
    listed = "; ".join(f"{item.step}: {item.reason}" for item in obstacles)
    super().__init__(
        f"the program cannot be scored at many positions in one pass: {listed}"
    )

batching_obstacles

batching_obstacles(program: MonadicProgram, latents: Collection[str], given: Collection[str]) -> tuple[BatchingObstacle, ...]

The steps of a program that cannot be evaluated at many positions.

PARAMETER DESCRIPTION
program

The program.

TYPE: MonadicProgram

latents

The sites whose values the position gives.

TYPE: Collection[str]

given

The sites and host data whose values every position shares.

TYPE: Collection[str]

RETURNS DESCRIPTION
tuple[BatchingObstacle, ...]

One entry per step, in the order the program runs them, those of the programs it calls and scans included. Empty for a program that can be scored at many positions.

Source code in src/quivers/effects/batching.py
def batching_obstacles(
    program: MonadicProgram,
    latents: Collection[str],
    given: Collection[str],
) -> tuple[BatchingObstacle, ...]:
    """The steps of a program that cannot be evaluated at many positions.

    Parameters
    ----------
    program : MonadicProgram
        The program.
    latents : Collection[str]
        The sites whose values the position gives.
    given : Collection[str]
        The sites and host data whose values every position shares.

    Returns
    -------
    tuple[BatchingObstacle, ...]
        One entry per step, in the order the program runs them, those of
        the programs it calls and scans included. Empty for a program
        that can be scored at many positions.
    """
    found: list[BatchingObstacle] = []
    depends = frozenset(latents)
    bound = frozenset({*latents, *given})
    for step in program.steps:
        names = _bound_names(step)
        inner = (
            step.program
            if isinstance(step, Call)
            else step.step
            if isinstance(step, Scan)
            else None
        )
        if isinstance(inner, MonadicProgram):
            own = inner_names(inner)
            found.extend(batching_obstacles(inner, depends | own, own))
        declared = _declaration(program, step)
        reason = declared.obstacle
        varying = sorted(declared.shared & depends)
        if reason is None and varying:
            reason = (
                f"it needs the same value of {varying} at every position, and that "
                "value depends on a latent"
            )
        if (
            reason is None
            and isinstance(step, Draw | Observe)
            and not bound.issuperset(names)
        ):
            reason = "its site is given no value, so every evaluation draws one"
        if reason is not None:
            found.append(
                BatchingObstacle(
                    step=f"{step.kind} step {', '.join(map(repr, names))}",
                    reason=reason,
                )
            )
        bound = bound.union(names)
        if not isinstance(step, Draw | Observe) and _positional(step, depends):
            depends = depends.union(names)
    return tuple(found)

inner_names

inner_names(program: MonadicProgram) -> frozenset[str]

The sites of a program another one runs.

PARAMETER DESCRIPTION
program

The called or scanned program.

TYPE: MonadicProgram

RETURNS DESCRIPTION
frozenset[str]

The names its draws bind. A site of it has a label of its own in the run, so whether it is given a value is checked when the run reaches it.

Source code in src/quivers/effects/batching.py
def inner_names(program: MonadicProgram) -> frozenset[str]:
    """The sites of a program another one runs.

    Parameters
    ----------
    program : MonadicProgram
        The called or scanned program.

    Returns
    -------
    frozenset[str]
        The names its draws bind. A site of it has a label of its own in
        the run, so whether it is given a value is checked when the run
        reaches it.
    """
    return frozenset(
        name
        for step in program.steps
        if isinstance(step, Draw | Observe)
        for name in step.names
    )

draws_at_random

draws_at_random(program: MonadicProgram) -> bool

Whether a program draws at random even when every site has a value.

PARAMETER DESCRIPTION
program

The program.

TYPE: MonadicProgram

RETURNS DESCRIPTION
bool

True when a let or score step of it, or of a program it calls or scans, declares that it draws.

Source code in src/quivers/effects/batching.py
def draws_at_random(program: MonadicProgram) -> bool:
    """Whether a program draws at random even when every site has a value.

    Parameters
    ----------
    program : MonadicProgram
        The program.

    Returns
    -------
    bool
        ``True`` when a let or score step of it, or of a program it calls
        or scans, declares that it draws.
    """
    for step in program.steps:
        inner = (
            step.program
            if isinstance(step, Call)
            else step.step
            if isinstance(step, Scan)
            else None
        )
        if isinstance(inner, MonadicProgram) and draws_at_random(inner):
            return True
        if _declaration(program, step).draws:
            return True
    return False