Skip to content

Scan Morphism

A scan carries a state from one position of a sequence to the next. ScanMorphism(cell) composes a cell, a kernel from an input and the previous state to the next state, once per position, as a time series transition draws the next state given the previous one. ScanMorphism.rsample(x) threads the hidden state through the sequence and returns the final state. ScanMorphism(cell, outputs="all") returns every state, of shape (batch, seq_len, hidden_dim), and ScanMorphism(cell, reverse=True) visits the positions from last to first while its trajectory, returned or scored, stays in input order.

ScanMorphism.rsample_trajectory(x) draws every state, and ScanMorphism.log_prob(x, trajectory) scores a trajectory as the sum of the log densities of its steps. A final state alone is refused, since its density is a marginal over the earlier states. ScanMorphism.log_joint(x, hidden_states) sums the same log densities and accepts the trajectory of hidden states either as a positional tensor or as a {state_key: tensor} dictionary, with state_key defaulting to "h".

ScanMorphism is the scan as a standalone morphism. Inside a MonadicProgram, the compiler binds every scan with a Scan step instead, whose step's sites are sites of the program addressed "<label>@<n>". A stochastic morphism cell draws at the scan's binding, and a program cell's sites keep their own labels. A program refuses a draw from a ScanMorphism.

scan

Scan combinator: temporal recurrence over sequences.

A ScanMorphism wraps a recurrent cell and applies it across a sequence, threading hidden state from one time step to the next. This implements the standard RNN pattern:

h_t = cell(x_t, h_{t-1})

where cell : A * H -> H is a morphism (either a plain ContinuousMorphism or a MonadicProgram) whose domain is a product of the per-timestep input space A and the hidden state space H, and whose codomain is H.

Given a cell : A * H -> H, scan(cell) produces a morphism A -> H that, at runtime:

  1. Expects a 3D input tensor of shape (batch, seq_len, dim_A).
  2. Initializes hidden state h_0 (zeros or a learned parameter).
  3. At each step t, concatenates x[:, t, :] with h to form the cell input, then calls cell.rsample to produce the new h.
  4. Returns the final hidden state h_T of shape (batch, dim_H), or, with outputs="all", every state, shape (batch, seq_len, dim_H).

With reverse=True the scan visits the positions from the last to the first, so its final state is the one after position 0; a returned trajectory is still laid out in input order, its entry t being the state after reading position t.

The scan's type in the categorical framework is:

scan(f : A x H -> H) : A -> H

where the sequence structure is implicit in the tensor's time dimension, following standard neural network conventions.

Initialization strategies
  • "zeros": h_0 = 0 (default).
  • "learned": h_0 is a learnable nn.Parameter.
Outputs
  • "last": the state after the last position visited (default).
  • "all": the state after every position, in input order.

Examples:

>>> from quivers.continuous.spaces import Euclidean, ProductSpace
>>> from quivers.continuous.families import ConditionalNormal
>>> A = Euclidean(name="input", dim=32)
>>> H = Euclidean(name="hidden", dim=64)
>>> cell = ConditionalNormal(ProductSpace(components=(A, H)), H)
>>> scanned = ScanMorphism(cell, init="zeros")
>>> scanned.domain   # Euclidean(name="input", dim=32)
>>> scanned.codomain # Euclidean(name="hidden", dim=64)
>>> x = torch.randn(8, 10, 32)  # batch=8, seq_len=10, input_dim=32
>>> h = scanned.rsample(x)      # (8, 64)

ScanMorphism

ScanMorphism(cell: ContinuousMorphism, init: str = 'zeros', outputs: Literal['last', 'all'] = 'last', reverse: bool = False)

Bases: ContinuousMorphism

Temporal scan: apply a recurrent cell across a sequence.

Wraps a cell morphism f : A * H -> H and produces a morphism A -> H that iterates over the time dimension of a 3D input tensor, threading hidden state forward.

This implements standard RNN-style recurrence::

h_0 = init
h_t = cell(concat(x_t, h_{t-1}))  for t = 1..T

The scan returns the final hidden state h_T, or every state.

PARAMETER DESCRIPTION
cell

The recurrent cell. Must have a product domain A * H and codomain H, where H matches the last component of the product domain.

TYPE: ContinuousMorphism

init

Initialization strategy for h_0: "zeros" (default), "learned" (trainable initial state), or an input label (scan(cell, init=h0)), which the apply step of an enclosing program binds to one of its values. A scan that starts from a label runs as a step of that program, which supplies the value; run on its own it has no initial state and raises.

TYPE: str DEFAULT: 'zeros'

outputs

"last" (default) returns the state after the last position the scan visits; "all" returns the state after every position, (batch, seq_len, hidden_dim) in input order.

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

reverse

Whether the scan visits the positions from the last to the first. A reversed scan's final state is the one after position 0, and its trajectory is still indexed by input position.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
ValueError

If init is not a strategy or a binding name, or outputs is neither "last" nor "all".

Source code in src/quivers/continuous/scan.py
def __init__(
    self,
    cell: ContinuousMorphism,
    init: str = "zeros",
    outputs: Literal["last", "all"] = "last",
    reverse: bool = False,
) -> None:
    input_space = _extract_input_space(cell)
    hidden_space = cell.codomain
    super().__init__(input_space, hidden_space)
    if outputs not in ("last", "all"):
        raise ValueError(
            f"unknown scan outputs {outputs!r}; expected 'last' or 'all'"
        )
    self._cell = cell
    self._init_strategy = init
    self._outputs: Literal["last", "all"] = outputs
    self._reverse = reverse
    self._input_dim = _event_dim(input_space)
    self._hidden_dim = _event_dim(hidden_space)
    if init == "learned":
        self._h0 = nn.Parameter(torch.zeros(self._hidden_dim))
    elif not init.isidentifier():
        raise ValueError(
            f"unknown init strategy {init!r}; expected 'zeros', 'learned', "
            f"or the name of a binding"
        )

cell property

The recurrent cell the scan applies at every position.

RETURNS DESCRIPTION
ContinuousMorphism

The cell A * H -> H.

outputs property

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

What the scan returns.

RETURNS DESCRIPTION
Literal['last', 'all']

"last" for the final state, "all" for every state.

reverse property

reverse: bool

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

RETURNS DESCRIPTION
bool

True for a right-to-left scan.

rsample

rsample(x: Tensor, sample_shape: Size = Size()) -> Tensor

Run the cell across the time dimension of x.

PARAMETER DESCRIPTION
x

Input sequence, in either layout _as_sequence reads: (batch, seq_len, input_dim) or the folded (batch, seq_len * input_dim).

TYPE: Tensor

sample_shape

Additional leading sample dimensions (applied to the cell's rsample at the first time step only).

TYPE: Size DEFAULT: Size()

RETURNS DESCRIPTION
Tensor

The final hidden state, shape (batch, hidden_dim), or with outputs="all" every state, (batch, seq_len, hidden_dim) in input order; sample_shape leads either when non-empty.

Source code in src/quivers/continuous/scan.py
def rsample(
    self, x: torch.Tensor, sample_shape: torch.Size = torch.Size()
) -> torch.Tensor:
    """Run the cell across the time dimension of x.

    Parameters
    ----------
    x : torch.Tensor
        Input sequence, in either layout
        `_as_sequence`
        reads: ``(batch, seq_len, input_dim)`` or the folded
        ``(batch, seq_len * input_dim)``.
    sample_shape : torch.Size
        Additional leading sample dimensions (applied to the
        cell's rsample at the first time step only).

    Returns
    -------
    torch.Tensor
        The final hidden state, shape ``(batch, hidden_dim)``, or
        with ``outputs="all"`` every state, ``(batch, seq_len,
        hidden_dim)`` in input order; ``sample_shape`` leads either
        when non-empty.
    """
    x = self._as_sequence(x)
    batch, seq_len, _ = x.shape
    h = self._initial_state(batch, x)
    states: dict[int, torch.Tensor] = {}
    for index, t in enumerate(self._order(seq_len)):
        x_t = x[:, t, :]
        cell_input = torch.cat([x_t, h], dim=-1)
        if index == 0 and len(sample_shape) > 0:
            h = self._cell.rsample(cell_input, sample_shape)
            h = self._flatten_cell_output(h)
            if len(sample_shape) > 0 and h.dim() > 2:
                x = x.unsqueeze(0).expand(*sample_shape, *x.shape)
        else:
            if h.dim() > 2:
                x_t = x[..., t, :]
                cell_input = torch.cat([x_t, h], dim=-1)
            h = self._cell.rsample(cell_input)
            h = self._flatten_cell_output(h)
        states[t] = h
    if self._outputs == "last":
        return h
    return torch.stack([states[t] for t in range(seq_len)], dim=-2)

base_dimension

base_dimension(x: Tensor) -> int | None

One cell's worth of coordinates per time step of the input.

The recurrence draws once per position, so its coordinate budget is the sequence length times the cell's own. The length is read off the input rather than declared, because scan(cell) : A -> H says nothing about how many positions a given input carries, and it is read through _as_sequence so a folded (batch, seq_len * input_dim) input reports the whole sequence's budget rather than one step's. Under-reporting it would hand push_base a block too short to run the recurrence on, and a chain that sliced its coordinates by that count would give every later factor the wrong ones.

Source code in src/quivers/continuous/scan.py
def base_dimension(self, x: torch.Tensor) -> int | None:
    """One cell's worth of coordinates per time step of the input.

    The recurrence draws once per position, so its coordinate
    budget is the sequence length times the cell's own. The length
    is read off the input rather than declared, because
    ``scan(cell) : A -> H`` says nothing about how many positions a
    given input carries, and it is read through
    `_as_sequence`
    so a folded ``(batch, seq_len * input_dim)`` input reports the
    whole sequence's budget rather than one step's. Under-reporting
    it would hand
    [`push_base`][quivers.continuous.scan.ScanMorphism.push_base]
    a block too short to run the recurrence on, and a chain that
    sliced its coordinates by that count would give every later
    factor the wrong ones.
    """
    seq = self._as_sequence(x)
    step = self._step_dimension(seq)
    if step is None:
        return None
    return int(seq.shape[1]) * step

push_base

push_base(x: Tensor, base: Tensor) -> Tensor

Run the recurrence on supplied coordinates instead of draws.

The k-th position the scan visits reads the k-th block of base, so the trajectory is a deterministic function of the coordinates and the input, and the same coordinates always produce the same value.

PARAMETER DESCRIPTION
x

Input sequence, in either layout _as_sequence reads.

TYPE: Tensor

base

Standard-normal coordinates, one cell's block per position.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The scan's value: the final state, or every state for outputs="all".

Source code in src/quivers/continuous/scan.py
def push_base(self, x: torch.Tensor, base: torch.Tensor) -> torch.Tensor:
    """Run the recurrence on supplied coordinates instead of draws.

    The ``k``-th position the scan visits reads the ``k``-th block
    of ``base``, so the trajectory is a deterministic function of
    the coordinates and the input, and the same coordinates always
    produce the same value.

    Parameters
    ----------
    x : torch.Tensor
        Input sequence, in either layout `_as_sequence` reads.
    base : torch.Tensor
        Standard-normal coordinates, one cell's block per position.

    Returns
    -------
    torch.Tensor
        The scan's value: the final state, or every state for
        ``outputs="all"``.
    """
    return self._value(self.trajectory_from_base(x, base))

push_base_scored

push_base_scored(x: Tensor, base: Tensor) -> tuple[Tensor, Tensor]

Run the recurrence on supplied coordinates and score its trajectory.

The coordinates select every state of the trajectory, not only the final one, so the draw's density is the trajectory's joint density, as a scan inside a program scores each position's site.

PARAMETER DESCRIPTION
x

Input sequence, in either layout _as_sequence reads.

TYPE: Tensor

base

Standard-normal coordinates, one cell's block per position.

TYPE: Tensor

RETURNS DESCRIPTION
tuple[Tensor, Tensor]

The scan's value (the final state, shape (batch, hidden_dim), or every state for outputs="all") and the trajectory's log-density, shape (batch,).

RAISES DESCRIPTION
ValueError

If the cell declares no reparameterization.

Source code in src/quivers/continuous/scan.py
def push_base_scored(
    self, x: torch.Tensor, base: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
    """Run the recurrence on supplied coordinates and score its trajectory.

    The coordinates select every state of the trajectory, not only
    the final one, so the draw's density is the trajectory's joint
    density, as a scan inside a program scores each position's
    site.

    Parameters
    ----------
    x : torch.Tensor
        Input sequence, in either layout `_as_sequence` reads.
    base : torch.Tensor
        Standard-normal coordinates, one cell's block per position.

    Returns
    -------
    tuple[torch.Tensor, torch.Tensor]
        The scan's value (the final state, shape ``(batch,
        hidden_dim)``, or every state for ``outputs="all"``) and the
        trajectory's log-density, shape ``(batch,)``.

    Raises
    ------
    ValueError
        If the cell declares no reparameterization.
    """
    trajectory = self.trajectory_from_base(x, base)
    return self._value(trajectory), self.log_prob(x, trajectory)

trajectory_from_base

trajectory_from_base(x: Tensor, base: Tensor) -> Tensor

Every state the recurrence reaches on supplied coordinates.

PARAMETER DESCRIPTION
x

Input sequence, in either layout _as_sequence reads.

TYPE: Tensor

base

Standard-normal coordinates, shape (batch, dimension) for the dimension base_dimension reports at x; the k-th position visited reads the k-th block.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The states :math:h_1, \ldots, h_T, shape (batch, seq_len, hidden_dim), in input order.

RAISES DESCRIPTION
ValueError

If the cell declares no reparameterization.

Source code in src/quivers/continuous/scan.py
def trajectory_from_base(self, x: torch.Tensor, base: torch.Tensor) -> torch.Tensor:
    """Every state the recurrence reaches on supplied coordinates.

    Parameters
    ----------
    x : torch.Tensor
        Input sequence, in either layout `_as_sequence` reads.
    base : torch.Tensor
        Standard-normal coordinates, shape ``(batch, dimension)``
        for the dimension `base_dimension` reports at ``x``; the
        ``k``-th position visited reads the ``k``-th block.

    Returns
    -------
    torch.Tensor
        The states :math:`h_1, \\ldots, h_T`, shape
        ``(batch, seq_len, hidden_dim)``, in input order.

    Raises
    ------
    ValueError
        If the cell declares no reparameterization.
    """
    seq = self._as_sequence(x)
    step = self._step_dimension(seq)
    if step is None:
        raise ValueError(
            f"ScanMorphism.push_base: the cell "
            f"{type(self._cell).__name__} declares no "
            f"reparameterization, so the recurrence has none either."
        )
    batch, seq_len, _ = seq.shape
    h = self._initial_state(batch, seq)
    states: dict[int, torch.Tensor] = {}
    for index, t in enumerate(self._order(seq_len)):
        cell_input = torch.cat([seq[:, t, :], h], dim=-1)
        block = base[:, index * step : (index + 1) * step]
        h = self._flatten_cell_output(self._cell.push_base(cell_input, block))
        states[t] = h
    return torch.stack([states[t] for t in range(seq_len)], dim=1)

rsample_trajectory

rsample_trajectory(x: Tensor) -> Tensor

Draw the recurrence's whole trajectory.

The trajectory is the value log_prob scores; for outputs="last", its state after the last position visited is what rsample returns, and for outputs="all" it is that value.

PARAMETER DESCRIPTION
x

Input sequence, in either layout _as_sequence reads.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The states :math:h_1, \ldots, h_T, shape (batch, seq_len, hidden_dim), in input order.

Source code in src/quivers/continuous/scan.py
def rsample_trajectory(self, x: torch.Tensor) -> torch.Tensor:
    """Draw the recurrence's whole trajectory.

    The trajectory is the value
    [`log_prob`][quivers.continuous.scan.ScanMorphism.log_prob]
    scores; for ``outputs="last"``, its state after the last
    position visited is what
    [`rsample`][quivers.continuous.scan.ScanMorphism.rsample]
    returns, and for ``outputs="all"`` it is that value.

    Parameters
    ----------
    x : torch.Tensor
        Input sequence, in either layout `_as_sequence` reads.

    Returns
    -------
    torch.Tensor
        The states :math:`h_1, \\ldots, h_T`, shape
        ``(batch, seq_len, hidden_dim)``, in input order.
    """
    seq = self._as_sequence(x)
    batch, seq_len, _ = seq.shape
    h = self._initial_state(batch, seq)
    states: dict[int, torch.Tensor] = {}
    for t in self._order(seq_len):
        cell_input = torch.cat([seq[:, t, :], h], dim=-1)
        h = self._flatten_cell_output(self._cell.rsample(cell_input))
        states[t] = h
    return torch.stack([states[t] for t in range(seq_len)], dim=1)

log_prob

log_prob(x: Tensor, y: Tensor) -> Tensor

Log-density of a supplied trajectory.

scan(cell) draws one state per position, and every one of them is a random variable, as a scan inside a program reaches one site per position. The value this method scores is thus the whole trajectory :math:h_{1:T}:

.. math::

\sum_{t=1}^{T} \log p(h_t \mid x_t, h_{t-1}),

with :math:h_{t+1} in place of :math:h_{t-1} for a reversed scan, whose trajectory is still indexed by input position.

The final state alone has a density only as a marginal over the states before it, which the scan does not compute, so a final state is refused rather than scored along a trajectory it does not determine. A one-position sequence's trajectory is its final state.

Floating-point reassociation in the recurrence may be amplified by later transitions, roughly an order of magnitude per step, so numerical comparisons should use the same cell implementation.

A cell with no conditional density contributes zero.

PARAMETER DESCRIPTION
x

Input sequence, in either layout _as_sequence reads.

TYPE: Tensor

y

The trajectory, shape (batch, seq_len, hidden_dim) or folded to (batch, seq_len * hidden_dim), as rsample_trajectory draws it.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Shape (batch,).

RAISES DESCRIPTION
ValueError

If y does not hold one state per position of x.

Source code in src/quivers/continuous/scan.py
def log_prob(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
    """Log-density of a supplied trajectory.

    ``scan(cell)`` draws one state per position, and every one of
    them is a random variable, as a scan inside a program reaches
    one site per position. The value this method scores is thus the
    whole trajectory :math:`h_{1:T}`:

    .. math::

        \\sum_{t=1}^{T} \\log p(h_t \\mid x_t, h_{t-1}),

    with :math:`h_{t+1}` in place of :math:`h_{t-1}` for a reversed
    scan, whose trajectory is still indexed by input position.

    The final state alone has a density only as a marginal over the
    states before it, which the scan does not compute, so a final
    state is refused rather than scored along a trajectory it does
    not determine. A one-position sequence's trajectory is its
    final state.

    Floating-point reassociation in the recurrence may be amplified
    by later transitions, roughly an order of magnitude per step, so
    numerical comparisons should use the same cell implementation.

    A cell with no conditional density contributes zero.

    Parameters
    ----------
    x : torch.Tensor
        Input sequence, in either layout
        `_as_sequence`
        reads.
    y : torch.Tensor
        The trajectory, shape ``(batch, seq_len, hidden_dim)`` or
        folded to ``(batch, seq_len * hidden_dim)``, as
        [`rsample_trajectory`][quivers.continuous.scan.ScanMorphism.rsample_trajectory]
        draws it.

    Returns
    -------
    torch.Tensor
        Shape ``(batch,)``.

    Raises
    ------
    ValueError
        If ``y`` does not hold one state per position of ``x``.
    """
    seq = self._as_sequence(x)
    batch, seq_len, _ = seq.shape
    if y.numel() != batch * seq_len * self._hidden_dim:
        raise ValueError(
            f"ScanMorphism.log_prob: scores the trajectory of "
            f"{seq_len} states of width {self._hidden_dim} per row, "
            f"shape ({batch}, {seq_len}, {self._hidden_dim}), but got "
            f"shape {tuple(y.shape)}; a final state alone has no "
            f"density the scan computes. Pass the trajectory, as "
            f"rsample_trajectory draws it."
        )
    if not self._cell.has_conditional_density():
        dtype = seq.dtype if seq.is_floating_point() else torch.get_default_dtype()
        return torch.zeros(batch, device=seq.device, dtype=dtype)
    return self.log_joint(seq, y)

log_joint

log_joint(x: Tensor, hidden_states: 'torch.Tensor | dict[str, torch.Tensor]', *, state_key: str = 'h') -> Tensor

Joint log-density given all intermediate hidden states.

Computes: log p(h_1, ..., h_T | x_{1:T}) = sum_t log p(h_t | x_t, h_{t-1})

over the positions in the order the scan visits them, so a reversed scan conditions each state on the one after it.

PARAMETER DESCRIPTION
x

Input sequence, in either layout _as_sequence reads.

TYPE: Tensor

hidden_states

All hidden states including final, shape (batch, seq_len, hidden_dim). May be passed positionally as a tensor or via a dict keyed by state_key (so the inference layer's standard log_joint(x, observations: dict) contract works without an adapter).

TYPE: Tensor | dict[str, Tensor]

state_key

Dict key under which the hidden-state tensor is looked up when hidden_states is a dict. Defaults to "h".

TYPE: str DEFAULT: 'h'

RETURNS DESCRIPTION
Tensor

Joint log-density. Shape (batch,).

Source code in src/quivers/continuous/scan.py
def log_joint(
    self,
    x: torch.Tensor,
    hidden_states: "torch.Tensor | dict[str, torch.Tensor]",
    *,
    state_key: str = "h",
) -> torch.Tensor:
    """Joint log-density given all intermediate hidden states.

    Computes:
        log p(h_1, ..., h_T | x_{1:T}) =
            sum_t log p(h_t | x_t, h_{t-1})

    over the positions in the order the scan visits them, so a
    reversed scan conditions each state on the one after it.

    Parameters
    ----------
    x : torch.Tensor
        Input sequence, in either layout
        `_as_sequence`
        reads.
    hidden_states : torch.Tensor | dict[str, torch.Tensor]
        All hidden states including final, shape
        ``(batch, seq_len, hidden_dim)``. May be passed
        positionally as a tensor or via a dict keyed by
        ``state_key`` (so the inference layer's standard
        ``log_joint(x, observations: dict)`` contract works
        without an adapter).
    state_key : str
        Dict key under which the hidden-state tensor is
        looked up when ``hidden_states`` is a dict. Defaults
        to ``"h"``.

    Returns
    -------
    torch.Tensor
        Joint log-density. Shape ``(batch,)``.
    """
    if isinstance(hidden_states, dict):
        hidden_states = hidden_states[state_key]
    seq = self._as_sequence(x)
    batch, seq_len, _ = seq.shape
    states = hidden_states.reshape(batch, seq_len, self._hidden_dim)
    h = self._initial_state(batch, seq)
    total = torch.zeros(batch, device=seq.device, dtype=h.dtype)
    for t in self._order(seq_len):
        h_t = states[:, t, :]
        cell_input = torch.cat([seq[:, t, :], h], dim=-1)
        total = total + self._cell.log_prob(cell_input, h_t)
        h = h_t
    return total