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:
- Expects a 3D input tensor of shape (batch, seq_len, dim_A).
- Initializes hidden state h_0 (zeros or a learned parameter).
- At each step t, concatenates x[:, t, :] with h to form the cell input, then calls cell.rsample to produce the new h.
- 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
TYPE:
|
init
|
Initialization strategy for h_0:
TYPE:
|
outputs
|
TYPE:
|
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:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/continuous/scan.py
cell
property
¶
cell: ContinuousMorphism
The recurrent cell the scan applies at every position.
| RETURNS | DESCRIPTION |
|---|---|
ContinuousMorphism
|
The cell |
outputs
property
¶
What the scan returns.
| RETURNS | DESCRIPTION |
|---|---|
Literal['last', 'all']
|
|
reverse
property
¶
Whether the scan visits the positions from the last to the first.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
rsample
¶
Run the cell across the time dimension of x.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
Input sequence, in either layout
TYPE:
|
sample_shape
|
Additional leading sample dimensions (applied to the cell's rsample at the first time step only). |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The final hidden state, shape |
Source code in src/quivers/continuous/scan.py
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
push_base
¶
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
TYPE:
|
base
|
Standard-normal coordinates, one cell's block per position.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The scan's value: the final state, or every state for
|
Source code in src/quivers/continuous/scan.py
push_base_scored
¶
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
TYPE:
|
base
|
Standard-normal coordinates, one cell's block per position.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Tensor, Tensor]
|
The scan's value (the final state, shape |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the cell declares no reparameterization. |
Source code in src/quivers/continuous/scan.py
trajectory_from_base
¶
Every state the recurrence reaches on supplied coordinates.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
Input sequence, in either layout
TYPE:
|
base
|
Standard-normal coordinates, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The states :math: |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the cell declares no reparameterization. |
Source code in src/quivers/continuous/scan.py
rsample_trajectory
¶
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
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The states :math: |
Source code in src/quivers/continuous/scan.py
log_prob
¶
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
TYPE:
|
y
|
The trajectory, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Shape |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/continuous/scan.py
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
TYPE:
|
hidden_states
|
All hidden states including final, shape
|
state_key
|
Dict key under which the hidden-state tensor is
looked up when
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Joint log-density. Shape |