Skip to content

Decoders

A decoder maps a vector to a distribution over terms of a signature. Decoder is a torch.nn.Module that implements a Kleisli arrow \(\mathrm{Vec}_D \to \mathcal{G}(T_\Sigma)\) of the Giry monad \(\mathcal{G}\), from vectors of dimension \(D\) to distributions over the terms \(T_\Sigma\) of the signature \(\Sigma\). It chooses a root constructor, generates its fields, and continues through the children. It has two operations, and reconstruction training raises the score of the original term:

  • sample(vec, ctx, sort) draws a single Term;
  • log_prob(term, vec, ctx, sort) scores an observed term under the same distribution.

Corecursion over a signature Σ proceeds as follows:

  1. At each sort position, the decoder produces logits over its choice set, every constructor and binder whose codomain is that sort, plus the built-in BoundVar whenever the context contains at least one in-scope variable of that sort.
  2. For the chosen operation, the decoder's factor head for that sort and arity splits the parent vector into one vector per child, and the decoder recurses on each child.
  3. Children of a data sort are sampled from a closed vocabulary by that sort's primitive head, and children of an index sort by binder_select over the variables in scope.
  4. Binder ops extend Γ before recursing on their scoped arguments, as in the encoder.

Construction sets a bound on the depth of recursion. At that bound, the decoder restricts the choice set to terminating ops. If a sort has no such op, the decoder raises an error that identifies the sort.

decoder

Decoder runtime: Markov kernels from code vectors to terms.

A Decoder is a Markov kernel R^D -> T_Σ from code vectors to the terms of a signature Σ, that is, a morphism R^D -> T_Σ of the Kleisli category of the distribution monad. It is a torch.nn.Module exposing two operations:

  • sample: draws a single Term from the distribution induced by an input vector.
  • log_prob: scores an observed term under the same distribution.

The corecursion structure over a signature Σ is:

  1. At each sort position, the decoder produces logits over its choice set: every constructor whose codomain is that sort, plus the built-in BOUND_VAR_OP whenever the context Γ contains at least one in-scope variable of that sort.
  2. For the chosen op, the parent vector is split into per-child sub-vectors by the per-(sort, arity) factor function, and the decoder recurses on each child under the same canonical form used by the encoder.
  3. Data-sorted children are sampled from a closed vocabulary via the per-sort primitive head; index-sorted children are sampled via binder_select over the in-scope variables.
  4. An argument that binds variables extends Γ by them before the decoder recurses on it, exactly mirroring the encoder.

Termination is depth-bounded at construction. At the budget limit the choice set is restricted to recursion-terminating ops (every child sort is data / index, never object); if no such op exists at a sort, the decoder raises.

No silent type coercion or sentinel value is ever emitted: an observed term whose shape doesn't match the canonical form raises.

Decoder

Decoder(name: str, signature: Signature, sort_dims: dict[str, int], depth: int, structure_fns: dict[str, Callable[[Tensor], Tensor]], primitive_fns: dict[str, Callable[[Tensor], Tensor]], factor_fns: dict[str, dict[int, Callable[[Tensor], tuple[Tensor, ...]]]], binder_select_fn: Callable[[Tensor, list[Tensor]], Tensor], data_vocab: dict[str, list[DataLeaf]], modules_owned: list[Module] | None = None)

Bases: Module

A Kleisli coalgebraic decoder over a signature.

PARAMETER DESCRIPTION
name

Identifier used in diagnostics.

TYPE: str

signature

The Σ whose terms this decoder generates.

TYPE: Signature

sort_dims

Per-sort embedding dimension.

TYPE: dict[str, int]

depth

Hard upper bound on recursion depth. Sampling beyond this depth is restricted to recursion-terminating ops at each sort.

TYPE: int

structure_fns

Per-sort logit producers (vec) -> Tensor. Indexed by sort name, plus a shared "*" entry consulted when no sort-specific entry exists.

TYPE: dict[str, callable]

primitive_fns

Per-data-sort logit producers over the closed token vocab.

TYPE: dict[str, callable]

factor_fns

Per-sort, per-arity child-vector projections (parent_vec) -> tuple[Tensor, …] of n sub-vectors.

TYPE: dict[str, dict[int, callable]]

binder_select_fn

(parent_vec, list_of_var_embeddings) -> Tensor of logits over the in-scope variables of a sort, used by BOUND_VAR_OP and by index-sorted child positions.

TYPE: callable

data_vocab

Per-data-sort closed vocabulary aligned with the column order of the corresponding primitive_fns output.

TYPE: dict[str, list]

modules_owned

Modules holding the parameters of the logit producers and projections, registered as submodules so their parameters train.

TYPE: list[Module] or None DEFAULT: None

RAISES DESCRIPTION
ValueError

If depth is not positive.

Source code in src/quivers/structural/decoder.py
def __init__(
    self,
    name: str,
    signature: Signature,
    sort_dims: dict[str, int],
    depth: int,
    structure_fns: dict[str, Callable[[torch.Tensor], torch.Tensor]],
    primitive_fns: dict[str, Callable[[torch.Tensor], torch.Tensor]],
    factor_fns: dict[
        str, dict[int, Callable[[torch.Tensor], tuple[torch.Tensor, ...]]]
    ],
    binder_select_fn: Callable[[torch.Tensor, list[torch.Tensor]], torch.Tensor],
    data_vocab: dict[str, list[DataLeaf]],
    modules_owned: list[nn.Module] | None = None,
) -> None:
    super().__init__()
    self.name = name
    self.signature = signature
    self.sort_dims = dict(sort_dims)
    if depth <= 0:
        raise ValueError(f"decoder {name!r}: depth must be positive, got {depth}")
    self.depth = depth
    self.structure_fns = dict(structure_fns)
    self.primitive_fns = dict(primitive_fns)
    self.factor_fns = {s: dict(fs) for s, fs in factor_fns.items()}
    self.binder_select_fn = binder_select_fn
    self.data_vocab = dict(data_vocab)
    self._candidates_by_sort = self._collect_candidates()
    # The closed terms of a bounded decoder's complete support and its
    # bound, set by `bound_support`; a decoder law draws among them.
    self.support_terms: tuple[Term, ...] | None = None
    self.support_limit: int | None = None
    for i, m in enumerate(modules_owned or []):
        self.add_module(f"_dec_{i}", m)

sample

sample(vec: Tensor, ctx: Context | None = None, sort: str | None = None) -> Term

Draw one term from the decoder's distribution.

PARAMETER DESCRIPTION
vec

The embedding to decode from.

TYPE: Tensor

ctx

The scope of in-scope bound variables; EMPTY_CONTEXT when omitted.

TYPE: Context or None DEFAULT: None

sort

The sort of the term to draw; the first declared object sort when omitted.

TYPE: str or None DEFAULT: None

RETURNS DESCRIPTION
Term

The sampled term.

RAISES DESCRIPTION
RuntimeError

If no sort is given and the signature has no object sort, or the decoder lacks a function, vocabulary, or candidate it needs at some position.

Source code in src/quivers/structural/decoder.py
def sample(
    self,
    vec: torch.Tensor,
    ctx: Context | None = None,
    sort: str | None = None,
) -> Term:
    """Draw one term from the decoder's distribution.

    Parameters
    ----------
    vec : torch.Tensor
        The embedding to decode from.
    ctx : Context or None
        The scope of in-scope bound variables; `EMPTY_CONTEXT`
        when omitted.
    sort : str or None
        The sort of the term to draw; the first declared object
        sort when omitted.

    Returns
    -------
    Term
        The sampled term.

    Raises
    ------
    RuntimeError
        If no sort is given and the signature has no object sort,
        or the decoder lacks a function, vocabulary, or candidate
        it needs at some position.
    """
    return self._decode_object(
        vec,
        ctx or EMPTY_CONTEXT,
        self._resolve_sort(sort),
        self.depth,
    )

bound_support

bound_support(limit: int) -> tuple[Term, ...]

Record the complete support at the principal sort, up to a bound.

PARAMETER DESCRIPTION
limit

The most terms the support may have.

TYPE: int

RETURNS DESCRIPTION
tuple of Term

The support, also kept as support_terms.

RAISES DESCRIPTION
ValueError

If the signature binds variables or complete_support refuses.

Source code in src/quivers/structural/decoder.py
def bound_support(self, limit: int) -> tuple[Term, ...]:
    """Record the complete support at the principal sort, up to a bound.

    Parameters
    ----------
    limit : int
        The most terms the support may have.

    Returns
    -------
    tuple of Term
        The support, also kept as ``support_terms``.

    Raises
    ------
    ValueError
        If the signature binds variables or `complete_support` refuses.
    """
    if not self.signature.is_first_order():
        raise ValueError("finite decoder support requires a first-order signature")
    terms = self.complete_support(self._resolve_sort(None), limit)
    self.support_terms = terms
    self.support_limit = limit
    return terms

complete_support

complete_support(sort: str, limit: int) -> tuple[Term, ...]

Every closed term the decoder can produce at a sort, counted first.

Every constructor the decoder can choose at a reachable sort and depth must be productive. Data leaves range over their decoder vocabulary, which must be finite, nonempty and free of duplicates. The support is counted up to limit before any term is made.

PARAMETER DESCRIPTION
sort

The root object sort.

TYPE: str

limit

The most terms to materialize; positive.

TYPE: int

RETURNS DESCRIPTION
tuple of Term

The full root support, in constructor and vocabulary order.

RAISES DESCRIPTION
ValueError

If the limit is not positive, a reachable branch can get stuck, a reachable sort needs a variable, or the support is larger than the limit.

Source code in src/quivers/structural/decoder.py
def complete_support(self, sort: str, limit: int) -> tuple[Term, ...]:
    """Every closed term the decoder can produce at a sort, counted first.

    Every constructor the decoder can choose at a reachable sort and
    depth must be productive. Data leaves range over their decoder
    vocabulary, which must be finite, nonempty and free of duplicates.
    The support is counted up to ``limit`` before any term is made.

    Parameters
    ----------
    sort : str
        The root object sort.
    limit : int
        The most terms to materialize; positive.

    Returns
    -------
    tuple of Term
        The full root support, in constructor and vocabulary order.

    Raises
    ------
    ValueError
        If the limit is not positive, a reachable branch can get stuck,
        a reachable sort needs a variable, or the support is larger
        than the limit.
    """
    if type(limit) is not int or limit < 1:
        raise ValueError(
            "a finite decoder support needs a positive candidate bound"
        )
    signature = self.signature
    root = (sort, self.depth)
    dependencies: TopologicalSorter[tuple[str, int]] = TopologicalSorter()
    productions: dict[
        tuple[str, int], tuple[tuple[str, tuple[tuple[str, int], ...]], ...]
    ] = {}
    leaves: dict[tuple[str, int], tuple[TermArg, ...]] = {}
    pending = [root]
    while pending:
        state = pending.pop()
        if state in productions or state in leaves:
            continue
        current, depth = state
        kind = signature.sorts[current].kind
        if kind == "data":
            words = tuple(self.data_vocab.get(current, ()))
            if not words or len(set(words)) != len(words):
                raise ValueError(
                    f"reachable decoder data sort {current!r} needs a nonempty "
                    "vocabulary without duplicates"
                )
            leaves[state] = words
            dependencies.add(state)
            continue
        if kind != "object":
            raise ValueError(
                f"reachable decoder sort {current!r} needs a variable in an "
                "empty context"
            )
        try:
            choices = self._object_candidates(EMPTY_CONTEXT, current, depth)
        except RuntimeError as error:
            raise ValueError(
                f"decoder sort {current!r} at depth {depth}: {error}"
            ) from error
        rules = tuple(
            (
                name,
                tuple(
                    (
                        child,
                        -1 if signature.sorts[child].kind == "data" else depth - 1,
                    )
                    for child in signature.constructors[name].domain
                ),
            )
            for name in choices
        )
        children = tuple(child for _, states in rules for child in states)
        productions[state] = rules
        dependencies.add(state, *children)
        pending.extend(children)
    order = tuple(dependencies.static_order())
    counts: dict[tuple[str, int], int] = {}
    overflow = limit + 1
    for state in order:
        if state in leaves:
            counts[state] = min(overflow, len(leaves[state]))
            continue
        total = 0
        for _, states in productions[state]:
            ways = 1
            for child in states:
                ways = min(overflow, ways * counts[child])
            total = min(overflow, total + ways)
        counts[state] = total
    if counts[root] > limit:
        raise ValueError(
            f"complete decoder support exceeds the {limit} candidate limit"
        )
    terms: dict[tuple[str, int], tuple[TermArg, ...]] = dict(leaves)
    for state in order:
        if state in productions:
            terms[state] = tuple(
                Term(op=name, args=tuple(arguments))
                for name, states in productions[state]
                for arguments in product(*(terms[child] for child in states))
            )
    found = terms[root]
    assert all(isinstance(term, Term) for term in found)
    return tuple(term for term in found if isinstance(term, Term))

log_prob

log_prob(term: Term, vec: Tensor, ctx: Context | None = None, sort: str | None = None) -> Tensor

Score an observed term under the decoder's distribution.

PARAMETER DESCRIPTION
term

The observed term.

TYPE: Term

vec

The embedding the term is decoded from.

TYPE: Tensor

ctx

The scope of in-scope bound variables; EMPTY_CONTEXT when omitted.

TYPE: Context or None DEFAULT: None

sort

The sort of term; the first declared object sort when omitted.

TYPE: str or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

The scalar log-probability of term.

RAISES DESCRIPTION
TypeError

If term is not a Term, or an argument does not match the kind of its sort.

RuntimeError

If the term's shape is outside the decoder's support, for instance an operation not in the choice set of its sort or a data value outside the closed vocabulary.

Source code in src/quivers/structural/decoder.py
def log_prob(
    self,
    term: Term,
    vec: torch.Tensor,
    ctx: Context | None = None,
    sort: str | None = None,
) -> torch.Tensor:
    """Score an observed term under the decoder's distribution.

    Parameters
    ----------
    term : Term
        The observed term.
    vec : torch.Tensor
        The embedding the term is decoded from.
    ctx : Context or None
        The scope of in-scope bound variables; `EMPTY_CONTEXT`
        when omitted.
    sort : str or None
        The sort of ``term``; the first declared object sort when
        omitted.

    Returns
    -------
    torch.Tensor
        The scalar log-probability of ``term``.

    Raises
    ------
    TypeError
        If ``term`` is not a `Term`, or an argument does not match
        the kind of its sort.
    RuntimeError
        If the term's shape is outside the decoder's support, for
        instance an operation not in the choice set of its sort or
        a data value outside the closed vocabulary.
    """
    if not isinstance(term, Term):
        raise TypeError(
            f"decoder {self.name!r}: log_prob expects a Term, got "
            f"{type(term).__name__}"
        )
    return self._logp_object(
        term,
        vec,
        ctx or EMPTY_CONTEXT,
        self._resolve_sort(sort),
        self.depth,
    )

decoder_draw_message

decoder_draw_message(name: str) -> str

The refusal of a program sample or observe from a decoder.

A decoder's values are structured terms, not the tensors a program's sites hold, so no program step draws from one; a loss scores a term under it instead.

PARAMETER DESCRIPTION
name

The decoder's name.

TYPE: str

RETURNS DESCRIPTION
str

The message.

Source code in src/quivers/structural/decoder.py
def decoder_draw_message(name: str) -> str:
    """The refusal of a program ``sample`` or ``observe`` from a decoder.

    A decoder's values are structured terms, not the tensors a program's
    sites hold, so no program step draws from one; a loss scores a term
    under it instead.

    Parameters
    ----------
    name : str
        The decoder's name.

    Returns
    -------
    str
        The message.
    """
    return (
        f"{name!r} is a decoder, whose values are terms of its signature, and "
        "a program step draws only tensor values; score a term under it in a "
        f"loss, as in `loss l [on=decoder({name})]` with body "
        f"`-{name}.log_prob(term, code)`, or sample terms in Python with "
        f"`{name}.sample(code)`"
    )