Skip to content

Packed forests

A plan whose retention is PackedForest keeps the derived hypergraph of a run. build_forest discovers the items from the input occurrences on an IndexedChart and stores, for each item, one ForestEdge per grounded rule instance concluding it and one per input occurrence of it. The result is a DerivationForest.

Lemma (unfoldings are derivations). The tree unfoldings of an item in the forest correspond one to one to its derivations, occurrence identities included.

Proof. A derivation of \(x\) is an input occurrence of \(x\), or a rule instance concluding \(x\) together with a derivation of each premise. The forest has exactly one edge per occurrence of \(x\), since occurrences are added as their own edges and never merged even when they share a slot and a binding, and exactly one edge per instance concluding \(x\), by the lemma that each instance is produced once (Plans). Unfolding chooses an edge at each node and recurses into its premises, so the two definitions agree by induction on the derivation. QED

Without the occurrence identities two inputs of one word at one position would be one leaf, and every count and statistic above them would be halved; the checks compare the unfoldings with the derivation oracle on exactly such an input.

Linear folds

forest_fold computes \(\bigoplus_d \bigotimes_{e \in d} \mathrm{value}(e)\), each derivation's product read as its factors are, the premises' values in order and then the edge's own. By distributivity, as for two-pass evaluation, the sum over the derivations of an item is the sum over its edges of the edge's product with its premises' sums, so dynamic programming over the forest in order computes it in time linear in the forest's size. A carrier such as the ExpectationSemiring makes the fold a statistic. forest_folds computes the folds of several goals in one pass, sharing the values of any premises used by more than one goal.

Nonlinear folds

nonlinear_fold computes \(\bigoplus_d h(d, w(d))\) for any \(h\). No aggregate summarizes it: for two derivations of weights \(-1\) and \(1\) and \(h\) the square, it is \(2\), while the square of the aggregate is \(0\). So every derivation is built, by fold_derivations, within a limit the caller declares.

fold_derivations_many lists the derivations of several goals under one limit. A repeated goal is counted once. Derivations are counted on the common subforest and the count includes zero-weight proofs. Each count saturates at one more than the limit. The saturated sum and product give the same budget decision as exact integers because the counts are nonnegative and multiplication by zero returns zero. The preflight uses one count update per edge and premise, with integers whose size is bounded by the declared limit.

If the count exceeds the limit, the forest raises ForestRefusal.TOO_MANY before building a derivation or calling a host interpretation. Otherwise it builds each premise derivation once for use by all the requested proofs above it. The single-goal call uses the same traversal.

Lemma (the limit bounds every list). Call a pair of an item and a height bound useful when it is the goal's, or a premise of an edge of a useful pair whose premises all have derivations within the bound. Every useful pair has at most as many derivations as the goal.

Proof. Let \((y, h)\) be a premise of a live edge of a useful pair \((x, h + 1)\). Fix a derivation within the bound for each other premise of the edge, which exists since the edge is live, and, by induction, an extension of the derivations of \(x\) to derivations of the goal. Substituting a derivation of \(y\) into that context gives a derivation of the goal, and distinct derivations of \(y\) give distinct ones. QED

The same argument applies with several roots by choosing any requested goal that uses the pair. The number of constructed rows is thus at most the limit times the number of useful pairs. The work also includes the rule arities and the cost of the chosen interpretation. See FOREST_WORK.

Heights and cycles

A forest with a cycle has items with infinitely many derivations. It is counted, folded and unfolded only within a bound on height, under the recursion contract Bounded with measure "height": an input or a rule without premises has height one, and a rule instance one more than its highest premise. Asked without a bound, the forest is refused with ForestRefusal.UNBOUNDED. A plan under bounded recursion refuses the two-pass run, whose meaning counts every derivation, and folds on the forest within Plan.height.

Expected proof embeddings

expected_embedding computes \(\sum_d p(d)\, \phi(d) / \sum_d p(d)\) for a fold \(\phi\) of derivations into vectors given as a HostInterpretation, with \(p(d)\) the derivation's weight as a nonnegative real. A neural fold is not linear, so the derivations are enumerated within the limit; each shared sub-derivation is folded once. encoder_interpretation makes an Encoder such a fold over the derivations of its signature's presentation, one Encoder.step per node, which equals the encoder applied to each derivation's term.

forest

Packed forests of derivations, with occurrence-sensitive provenance.

A packed forest is the derived hypergraph of a run: every item, and for each item every grounded rule instance concluding it and every input occurrence of it, as an edge to its premise items. Two occurrences of one item stay two edges, so the derivations a forest unfolds into are the derivations of the presentation, occurrence identities included, one to one.

Three kinds of observation are computed from a forest.

  • A linear proof fold, the sum over derivations of the product of a value per edge, by dynamic programming over the forest in premise order; an expectation or other carrier makes it a statistic.
  • A nonlinear fold, the sum over derivations of any function of the derivation and its weight, by enumerating the derivations. It needs them all, so a declared limit on their number is checked before any is built, and a forest with more is refused, never truncated.
  • An expected proof embedding, the weighted mean of a fold of each derivation into vectors, by enumeration in which each shared sub-derivation is folded once.

A cyclic forest has infinitely many derivations; it is unfolded only under a declared bound on their height.

Key

Key = tuple[Item, int | None]

An item and the bound on the height of its derivations, None for none.

InputId

A rule's parameter, or an input occurrence.

Listed

Listed = list[tuple[Derivation, Tensor, V]]

Derivations of one item, each with its weight and its fold.

ForestRefusal

Bases: str, Enum

Why a forest is not unfolded.

ForestRefused

ForestRefused(code: ForestRefusal, reason: str)

Bases: ValueError

A forest is not unfolded, with the reason.

PARAMETER DESCRIPTION
code

The kind of reason.

TYPE: ForestRefusal

reason

The reason.

TYPE: str

Source code in src/quivers/stochastic/forest.py
def __init__(self, code: ForestRefusal, reason: str) -> None:
    super().__init__(f"{code.value}: {reason}")
    self.code = code
    self.reason = reason

ForestEdge didactic-model

ForestEdge(*, constructor: ConstructorId = field(opaque=True, extras=OPAQUE_BY_VALUE), binding: tuple[tuple[str, Ground], ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), premises: tuple[Item, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), occurrence: OccurrenceId | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), values: tuple[str | int | float | bool, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

One way an item is derived: a rule instance or an input occurrence.

PARAMETER DESCRIPTION
constructor

The rule, or the input's slot.

TYPE: ConstructorId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

binding

The rule's or slot's variables.

TYPE: tuple of tuple of str and Ground DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

premises

The premise items in premise order; none for an input.

TYPE: tuple of Item DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

occurrence

The input occurrence; None for a rule instance.

TYPE: OccurrenceId or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

values

The occurrence's values; none for a rule instance.

TYPE: tuple of str or int or float or bool DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

DerivationForest didactic-model

DerivationForest(*, presentation: RulePresentation = field(opaque=True, extras=OPAQUE_BY_VALUE), items: tuple[Item, ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), edges: dict[Item, tuple[ForestEdge, ...]] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), order: tuple[Item, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), work: ChartWork = field(default=ChartWork(), opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

The derived hypergraph of a run.

PARAMETER DESCRIPTION
presentation

The presentation.

TYPE: RulePresentation DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

items

Every item, in the order discovered.

TYPE: tuple of Item DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

edges

The edges concluding each item: its input occurrences, then its rule instances, in the order found.

TYPE: dict of Item to tuple of ForestEdge DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

order

The items in an order in which every premise precedes its conclusions, or None when the hypergraph has a cycle.

TYPE: tuple of Item or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

work

The counters of the chart that found the edges.

TYPE: ChartWork DEFAULT: field(default=ChartWork(), opaque=True, extras=OPAQUE_BY_IDENTITY)

acyclic property

acyclic: bool

Whether the hypergraph has no cycle.

RETURNS DESCRIPTION
bool

True when every item has finitely many derivations.

size property

size: int

The number of edges and premise references, the forest's size.

RETURNS DESCRIPTION
int

sum_e (1 + |premises(e)|).

report

report() -> WorkReport

The work of building the forest.

RETURNS DESCRIPTION
WorkReport

The chart's lookups and candidates, and the forest's size as its provenance, each measured.

Source code in src/quivers/stochastic/forest.py
def report(self) -> WorkReport:
    """The work of building the forest.

    Returns
    -------
    WorkReport
        The chart's lookups and candidates, and the forest's size as
        its provenance, each measured.
    """
    chart = self.work.report(Phase.CONSTRUCTION)
    return chart.with_(
        provenance_records=self.size,
        measured=measuring((*chart.measured, WorkField.PROVENANCE_RECORDS)),
    )

count

count(goal: Item, *, height: int | None = None) -> int

The number of derivations of an item, exactly.

PARAMETER DESCRIPTION
goal

The item.

TYPE: Item

height

The greatest height of a derivation counted; required when the forest has a cycle. An input has height one.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
int

The count, zero for an item not in the forest.

RAISES DESCRIPTION
ForestRefused

If the forest has a cycle and no height is given.

Source code in src/quivers/stochastic/forest.py
def count(self, goal: Item, *, height: int | None = None) -> int:
    """The number of derivations of an item, exactly.

    Parameters
    ----------
    goal : Item
        The item.
    height : int or None
        The greatest height of a derivation counted; required when
        the forest has a cycle. An input has height one.

    Returns
    -------
    int
        The count, zero for an item not in the forest.

    Raises
    ------
    ForestRefused
        If the forest has a cycle and no height is given.
    """
    if goal not in self.edges:
        return 0
    counts = _counts(self.below(goal), height)
    return counts.get((goal, height), 0)

below

below(goal: Item) -> DerivationForest

The part of the forest that derivations of one item use.

PARAMETER DESCRIPTION
goal

The item.

TYPE: Item

RETURNS DESCRIPTION
DerivationForest

The items reachable from goal through premises, with their edges, in the same orders.

Source code in src/quivers/stochastic/forest.py
def below(self, goal: Item) -> DerivationForest:
    """The part of the forest that derivations of one item use.

    Parameters
    ----------
    goal : Item
        The item.

    Returns
    -------
    DerivationForest
        The items reachable from ``goal`` through premises, with
        their edges, in the same orders.
    """
    return self.below_all((goal,))

below_all

below_all(goals: Sequence[Item]) -> DerivationForest

The part of the forest used by derivations of any of the goals.

PARAMETER DESCRIPTION
goals

The requested items.

TYPE: Sequence of Item

RETURNS DESCRIPTION
DerivationForest

The items reachable from the goals through premises, with their edges, in the same orders.

Source code in src/quivers/stochastic/forest.py
def below_all(self, goals: Sequence[Item]) -> DerivationForest:
    """The part of the forest used by derivations of any of the goals.

    Parameters
    ----------
    goals : Sequence of Item
        The requested items.

    Returns
    -------
    DerivationForest
        The items reachable from the goals through premises, with their
        edges, in the same orders.
    """
    reached = set(goals)
    stack = list(reached)
    while stack:
        item = stack.pop()
        for edge in self.edges.get(item, ()):
            for premise in edge.premises:
                if premise not in reached:
                    reached.add(premise)
                    stack.append(premise)
    return DerivationForest(
        presentation=self.presentation,
        items=tuple(item for item in self.items if item in reached),
        edges={item: self.edges[item] for item in reached if item in self.edges},
        order=None
        if self.order is None
        else tuple(item for item in self.order if item in reached),
    )

build_forest

build_forest(presentation: RulePresentation, axioms: Sequence[AxiomOccurrence]) -> DerivationForest

The packed forest of a presentation over input occurrences.

Items are discovered from the inputs, and each instance is found once, by the last of its premises to be discovered, and stored as an edge of its conclusion. Rules without premises are edges of their ground conclusions. The forest is then ordered so premises precede conclusions, when it has no cycle.

PARAMETER DESCRIPTION
presentation

The presentation; no premise may have hypotheses.

TYPE: RulePresentation

axioms

The input occurrences, each kept as its own edge.

TYPE: Sequence of AxiomOccurrence

RETURNS DESCRIPTION
DerivationForest

The forest.

RAISES DESCRIPTION
ForestRefused

If an occurrence names no slot of the presentation.

Source code in src/quivers/stochastic/forest.py
def build_forest(
    presentation: RulePresentation, axioms: Sequence[AxiomOccurrence]
) -> DerivationForest:
    """The packed forest of a presentation over input occurrences.

    Items are discovered from the inputs, and each instance is found once,
    by the last of its premises to be discovered, and stored as an edge of
    its conclusion. Rules without premises are edges of their ground
    conclusions. The forest is then ordered so premises precede
    conclusions, when it has no cycle.

    Parameters
    ----------
    presentation : RulePresentation
        The presentation; no premise may have hypotheses.
    axioms : Sequence of AxiomOccurrence
        The input occurrences, each kept as its own edge.

    Returns
    -------
    DerivationForest
        The forest.

    Raises
    ------
    ForestRefused
        If an occurrence names no slot of the presentation.
    """
    chart = IndexedChart(presentation)
    edges: dict[Item, list[ForestEdge]] = {}
    discovered: list[Item] = []
    seen: set[Item] = set()
    queue: deque[Item] = deque()

    def reach(item: Item) -> None:
        """Note an item, queueing it when new.

        Parameters
        ----------
        item : Item
            The item.
        """
        if item not in seen:
            seen.add(item)
            discovered.append(item)
            queue.append(item)

    for occurrence in axioms:
        slot = presentation.constructors_by_id.get(occurrence.slot)
        if not isinstance(slot, AxiomSlot):
            raise ForestRefused(ForestRefusal.MISSING, "an occurrence names no slot")
        binding = dict(occurrence.binding)
        item = chart.items.intern(
            slot.judgment.family,
            tuple(evaluate_index(a, binding) for a in slot.judgment.arguments),
        )
        _add_input(
            edges,
            item,
            ForestEdge(
                constructor=slot.id,
                binding=occurrence.binding,
                occurrence=occurrence.occurrence,
                values=occurrence.values,
            ),
        )
        reach(item)
    for rule in presentation.rules:
        if rule.premises or not chart.holds(rule, {}):
            continue
        item = chart.items.intern(
            rule.conclusion.family,
            tuple(evaluate_index(a, {}) for a in rule.conclusion.arguments),
        )
        edges.setdefault(item, []).append(ForestEdge(constructor=rule.id))
        reach(item)
    admitted: set[Item] = set()
    by_premise = presentation.rules_by_premise
    while queue:
        item = queue.popleft()
        admitted.add(item)
        chart.add(item)
        for rule, position in by_premise.get(item.family, ()):
            for binding, premises in chart.instances(
                rule, position, item, admitted.__contains__
            ):
                conclusion = chart.items.intern(
                    rule.conclusion.family,
                    tuple(
                        evaluate_index(a, binding) for a in rule.conclusion.arguments
                    ),
                )
                edges.setdefault(conclusion, []).append(
                    ForestEdge(
                        constructor=rule.id,
                        binding=tuple(sorted(binding.items())),
                        premises=premises,
                    )
                )
                reach(conclusion)
    frozen = {item: tuple(found) for item, found in edges.items()}
    return DerivationForest(
        presentation=presentation,
        items=tuple(discovered),
        edges=frozen,
        order=_topological(discovered, frozen),
        work=chart.counters(),
    )

edge_weight

edge_weight(forest: DerivationForest, edge: ForestEdge, algebra: OrderPreservingSemiring, inputs: Mapping[InputId, Tensor], *, like: Tensor) -> Tensor

The weight of an edge, as a plan weighs it.

An input occurrence takes its own weight, else its slot's parameter; a rule instance takes its rule's parameter; a missing weight is the unit.

PARAMETER DESCRIPTION
forest

The forest.

TYPE: DerivationForest

edge

The edge.

TYPE: ForestEdge

algebra

The algebra.

TYPE: OrderPreservingSemiring

inputs

The weights.

TYPE: Mapping of InputId to torch.Tensor

like

The dtype and device of the unit.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The weight.

RAISES DESCRIPTION
ForestRefused

If the rule's weight needs an executable attachment.

Source code in src/quivers/stochastic/forest.py
def edge_weight(
    forest: DerivationForest,
    edge: ForestEdge,
    algebra: OrderPreservingSemiring,
    inputs: Mapping[InputId, torch.Tensor],
    *,
    like: torch.Tensor,
) -> torch.Tensor:
    """The weight of an edge, as a plan weighs it.

    An input occurrence takes its own weight, else its slot's parameter;
    a rule instance takes its rule's parameter; a missing weight is the
    unit.

    Parameters
    ----------
    forest : DerivationForest
        The forest.
    edge : ForestEdge
        The edge.
    algebra : OrderPreservingSemiring
        The algebra.
    inputs : Mapping of InputId to torch.Tensor
        The weights.
    like : torch.Tensor
        The dtype and device of the unit.

    Returns
    -------
    torch.Tensor
        The weight.

    Raises
    ------
    ForestRefused
        If the rule's weight needs an executable attachment.
    """
    constructor = forest.presentation.constructors_by_id[edge.constructor]
    assert isinstance(constructor, (Rule, AxiomSlot))
    if isinstance(constructor.weight, ComputedRuleWeight):
        raise ForestRefused(
            ForestRefusal.MISSING,
            "the forest has no executable attachment for this computed rule weight",
        )
    if edge.occurrence is not None and edge.occurrence in inputs:
        return inputs[edge.occurrence]
    if constructor.weight is not None and constructor.weight in inputs:
        return inputs[constructor.weight]
    return algebra.unit_like((), like)

forest_fold

forest_fold(forest: DerivationForest, goal: Item, algebra: OrderPreservingSemiring, value: Callable[[ForestEdge], Tensor], *, like: Tensor, height: int | None = None) -> Tensor

A linear proof fold: the sum over derivations of the product of edge values.

Each derivation's product is read as its factors are: the premises' values in order, then the edge's own. Dynamic programming over the forest computes it in time linear in the forest's size, times the height bound when one is given.

PARAMETER DESCRIPTION
forest

The forest.

TYPE: DerivationForest

goal

The item.

TYPE: Item

algebra

The algebra of the values.

TYPE: OrderPreservingSemiring

value

The value of each edge.

TYPE: Callable[[ForestEdge], Tensor]

like

The dtype and device of the zero.

TYPE: Tensor

height

The bound on height, required for a cyclic forest.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

The fold, zero when the goal has no derivation.

RAISES DESCRIPTION
ForestRefused

If the forest has a cycle and no height is given.

Source code in src/quivers/stochastic/forest.py
def forest_fold(
    forest: DerivationForest,
    goal: Item,
    algebra: OrderPreservingSemiring,
    value: Callable[[ForestEdge], torch.Tensor],
    *,
    like: torch.Tensor,
    height: int | None = None,
) -> torch.Tensor:
    """A linear proof fold: the sum over derivations of the product of edge values.

    Each derivation's product is read as its factors are: the premises'
    values in order, then the edge's own. Dynamic programming over the
    forest computes it in time linear in the forest's size, times the
    height bound when one is given.

    Parameters
    ----------
    forest : DerivationForest
        The forest.
    goal : Item
        The item.
    algebra : OrderPreservingSemiring
        The algebra of the values.
    value : Callable[[ForestEdge], torch.Tensor]
        The value of each edge.
    like : torch.Tensor
        The dtype and device of the zero.
    height : int or None
        The bound on height, required for a cyclic forest.

    Returns
    -------
    torch.Tensor
        The fold, zero when the goal has no derivation.

    Raises
    ------
    ForestRefused
        If the forest has a cycle and no height is given.
    """
    return forest_folds(forest, (goal,), algebra, value, like=like, height=height)[goal]

forest_folds

forest_folds(forest: DerivationForest, goals: Sequence[Item], algebra: OrderPreservingSemiring, value: Callable[[ForestEdge], Tensor], *, like: Tensor, height: int | None = None) -> dict[Item, Tensor]

Evaluate linear proof folds sharing one table for all requested items.

For each incoming edge, the premise occurrences independently choose derivations of their items. Distributivity factors this sum of products into the product of the already-computed premise sums and the edge's value. Repeated occurrences of an item each contribute a factor.

PARAMETER DESCRIPTION
forest

The forest.

TYPE: DerivationForest

goals

The requested items.

TYPE: Sequence of Item

algebra

The algebra of the values.

TYPE: OrderPreservingSemiring

value

The value of each edge.

TYPE: Callable[[ForestEdge], Tensor]

like

The dtype and device of the zero.

TYPE: Tensor

height

The bound on height, required for a cyclic forest.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
dict of Item to torch.Tensor

The requested folds, with zero for any goal with no derivation.

RAISES DESCRIPTION
ForestRefused

If the forest has a cycle and no height is given.

Source code in src/quivers/stochastic/forest.py
def forest_folds(
    forest: DerivationForest,
    goals: Sequence[Item],
    algebra: OrderPreservingSemiring,
    value: Callable[[ForestEdge], torch.Tensor],
    *,
    like: torch.Tensor,
    height: int | None = None,
) -> dict[Item, torch.Tensor]:
    """Evaluate linear proof folds sharing one table for all requested items.

    For each incoming edge, the premise occurrences independently choose
    derivations of their items. Distributivity factors this sum of products
    into the product of the already-computed premise sums and the edge's
    value. Repeated occurrences of an item each contribute a factor.

    Parameters
    ----------
    forest : DerivationForest
        The forest.
    goals : Sequence of Item
        The requested items.
    algebra : OrderPreservingSemiring
        The algebra of the values.
    value : Callable[[ForestEdge], torch.Tensor]
        The value of each edge.
    like : torch.Tensor
        The dtype and device of the zero.
    height : int or None
        The bound on height, required for a cyclic forest.

    Returns
    -------
    dict of Item to torch.Tensor
        The requested folds, with zero for any goal with no derivation.

    Raises
    ------
    ForestRefused
        If the forest has a cycle and no height is given.
    """
    part = forest.below_all(goals)

    values: dict[Key, torch.Tensor] = {}
    for level in _levels(part, height):
        for key in level:
            below = _below(key)
            total: torch.Tensor | None = None
            for edge in part.edges.get(key[0], ()):
                if edge.occurrence is None and below is not None and below < 0:
                    continue
                premises = [(premise, below) for premise in edge.premises]
                if not all(premise in values for premise in premises):
                    continue
                weight = value(edge)
                term = weight
                if premises:
                    first, *rest = premises
                    term = values[first]
                    for premise in rest:
                        term = algebra.tensor_op(term, values[premise])
                    term = algebra.tensor_op(term, weight)
                total = term if total is None else _join(algebra, total, term)
            if total is not None:
                values[key] = total
    return {
        goal: values[(goal, height)]
        if (goal, height) in values
        else algebra.zero_like((), like)
        for goal in goals
    }

fold_derivations

fold_derivations(forest: DerivationForest, goal: Item, algebra: OrderPreservingSemiring, inputs: Mapping[InputId, Tensor], interpretation: HostInterpretation[V], *, limit: int, like: Tensor, height: int | None = None) -> Listed[V]

Every derivation of an item, with its weight and its fold.

Derivations are built bottom up and shared: a derivation of a premise is built and folded once and reused by every derivation above it. The exact budget decision happens before any derivation is built.

PARAMETER DESCRIPTION
forest

The forest.

TYPE: DerivationForest

goal

The item.

TYPE: Item

algebra

The algebra of the weights.

TYPE: OrderPreservingSemiring

inputs

The weights.

TYPE: Mapping of InputId to torch.Tensor

interpretation

The fold of a derivation; its operations receive each node and its premises' folds.

TYPE: HostInterpretation

limit

The most derivations of the goal to build, declared by the caller.

TYPE: int

like

The dtype and device of the unit.

TYPE: Tensor

height

The bound on height, required for a cyclic forest.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
list of tuple of Derivation, torch.Tensor and V

Every derivation of the goal, its weight and its fold.

RAISES DESCRIPTION
ForestRefused

If the goal has more derivations than limit, or the forest has a cycle and no height is given.

Source code in src/quivers/stochastic/forest.py
def fold_derivations[V](
    forest: DerivationForest,
    goal: Item,
    algebra: OrderPreservingSemiring,
    inputs: Mapping[InputId, torch.Tensor],
    interpretation: HostInterpretation[V],
    *,
    limit: int,
    like: torch.Tensor,
    height: int | None = None,
) -> Listed[V]:
    """Every derivation of an item, with its weight and its fold.

    Derivations are built bottom up and shared: a derivation of a premise
    is built and folded once and reused by every derivation above it.
    The exact budget decision happens before any derivation is built.

    Parameters
    ----------
    forest : DerivationForest
        The forest.
    goal : Item
        The item.
    algebra : OrderPreservingSemiring
        The algebra of the weights.
    inputs : Mapping of InputId to torch.Tensor
        The weights.
    interpretation : HostInterpretation
        The fold of a derivation; its operations receive each node and
        its premises' folds.
    limit : int
        The most derivations of the goal to build, declared by the caller.
    like : torch.Tensor
        The dtype and device of the unit.
    height : int or None
        The bound on height, required for a cyclic forest.

    Returns
    -------
    list of tuple of Derivation, torch.Tensor and V
        Every derivation of the goal, its weight and its fold.

    Raises
    ------
    ForestRefused
        If the goal has more derivations than ``limit``, or the forest
        has a cycle and no height is given.
    """
    return fold_derivations_many(
        forest,
        (goal,),
        algebra,
        inputs,
        interpretation,
        limit=limit,
        like=like,
        height=height,
    )[goal]

fold_derivations_many

fold_derivations_many(forest: DerivationForest, goals: Sequence[Item], algebra: OrderPreservingSemiring, inputs: Mapping[InputId, Tensor], interpretation: HostInterpretation[V], *, limit: int, like: Tensor, height: int | None = None, node_limit: int | None = None) -> dict[Item, Listed[V]]

List several goals' derivations under one exact global proof budget.

Count structural proofs over the common subforest in one pass, saturating integers at one above the larger of the active limits. Every useful subtree extends to a requested proof, so each list in a successful run has at most limit entries. Build and fold each sub-derivation once across all goals. This sharing applies to host interpretations whose operations may be reused. The count includes zero-weight structural proofs.

PARAMETER DESCRIPTION
forest

The common forest of the requested goals.

TYPE: DerivationForest

goals

The roots to list. A repeated goal is counted and returned once, at its first position.

TYPE: Sequence of Item

algebra

The algebra of each derivation's weight.

TYPE: OrderPreservingSemiring

inputs

The rule and occurrence weights.

TYPE: Mapping of InputId to torch.Tensor

interpretation

The fold performed on each listed derivation.

TYPE: HostInterpretation

limit

The maximum total number of proofs of the distinct goals.

TYPE: int

like

The dtype and device of the unit.

TYPE: Tensor

height

The bound on height, required for a cyclic forest.

TYPE: int or None DEFAULT: None

node_limit

An optional global limit on the sum of the unfolded proof sizes of those goals. Repeated subtree occurrences each count, even when the listing stores their derivations once.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
dict of Item to Listed

Every requested goal's derivations, with weights and folds.

RAISES DESCRIPTION
ForestRefused

If there are more proofs or unfolded nodes than the limits allow, or the forest has an unbounded cycle.

ValueError

If a proof budget is negative.

Source code in src/quivers/stochastic/forest.py
def fold_derivations_many[V](
    forest: DerivationForest,
    goals: Sequence[Item],
    algebra: OrderPreservingSemiring,
    inputs: Mapping[InputId, torch.Tensor],
    interpretation: HostInterpretation[V],
    *,
    limit: int,
    like: torch.Tensor,
    height: int | None = None,
    node_limit: int | None = None,
) -> dict[Item, Listed[V]]:
    """List several goals' derivations under one exact global proof budget.

    Count structural proofs over the common subforest in one pass,
    saturating integers at one above the larger of the active limits.
    Every useful subtree extends to
    a requested proof, so each list in a successful run has at most
    ``limit`` entries. Build and fold each sub-derivation once across all
    goals. This sharing applies to host interpretations whose operations
    may be reused. The count includes zero-weight structural proofs.

    Parameters
    ----------
    forest : DerivationForest
        The common forest of the requested goals.
    goals : Sequence of Item
        The roots to list. A repeated goal is counted and returned once,
        at its first position.
    algebra : OrderPreservingSemiring
        The algebra of each derivation's weight.
    inputs : Mapping of InputId to torch.Tensor
        The rule and occurrence weights.
    interpretation : HostInterpretation
        The fold performed on each listed derivation.
    limit : int
        The maximum total number of proofs of the distinct goals.
    like : torch.Tensor
        The dtype and device of the unit.
    height : int or None
        The bound on height, required for a cyclic forest.
    node_limit : int or None
        An optional global limit on the sum of the unfolded proof sizes
        of those goals. Repeated subtree occurrences each count, even
        when the listing stores their derivations once.

    Returns
    -------
    dict of Item to Listed
        Every requested goal's derivations, with weights and folds.

    Raises
    ------
    ForestRefused
        If there are more proofs or unfolded nodes than the limits allow,
        or the forest has an unbounded cycle.
    ValueError
        If a proof budget is negative.
    """
    if limit < 0:
        raise ValueError("the proof budget must be nonnegative")
    if node_limit is not None and node_limit < 0:
        raise ValueError("the proof node budget must be nonnegative")
    goals = tuple(dict.fromkeys(goals))
    if not goals:
        return {}
    part = forest.below_all(goals)
    cap = max(limit, node_limit or 0) + 1
    sizes: dict[Key, int] = {}
    if node_limit is None:
        counts = _counts(part, height, cap=cap)
        total = sum(counts.get((goal, height), 0) for goal in goals)
    else:
        counts = _counts(part, height, cap=cap, sizes=sizes)
        total = 0
        for goal in goals:
            total += counts.get((goal, height), 0)
            if total > limit:
                break
    if total > limit:
        raise ForestRefused(
            ForestRefusal.TOO_MANY,
            f"at least {total} derivations exceed the declared limit of {limit}; "
            "none is returned",
        )
    if node_limit is not None:
        nodes = 0
        for goal in goals:
            nodes += sizes.get((goal, height), 0)
            if nodes > node_limit:
                raise ForestRefused(
                    ForestRefusal.TOO_MANY_NODES,
                    f"at least {nodes} unfolded proof nodes exceed the declared "
                    f"node limit of {node_limit}; none is returned",
                )
    useful = _useful(part, goals, height, counts)
    operations = interpretation.operations
    listed: dict[Key, Listed[V]] = {}
    for level in _levels(part, height):
        for key in level:
            if key not in useful:
                continue
            item = key[0]
            below = _below(key)
            found: Listed[V] = []
            for edge in part.edges.get(item, ()):
                weight = edge_weight(part, edge, algebra, inputs, like=like)
                if edge.occurrence is not None:
                    node = Derivation(
                        constructor=edge.constructor,
                        item=item,
                        binding=edge.binding,
                        values=edge.values,
                        occurrence=edge.occurrence,
                    )
                    found.append((node, weight, operations[edge.constructor](node, ())))
                    continue
                premises = [(premise, below) for premise in edge.premises]
                if not all(premise in listed for premise in premises):
                    continue
                for choice in _choices([listed[premise] for premise in premises]):
                    node = Derivation(
                        constructor=edge.constructor,
                        item=item,
                        binding=edge.binding,
                        premises=tuple(derivation for derivation, _, _ in choice),
                    )
                    product = weight
                    if choice:
                        product = choice[0][1]
                        for _, factor, _ in choice[1:]:
                            product = algebra.tensor_op(product, factor)
                        product = algebra.tensor_op(product, weight)
                    folds: tuple[PremiseValue[V], ...] = tuple(
                        folded for _, _, folded in choice
                    )
                    found.append(
                        (node, product, operations[edge.constructor](node, folds))
                    )
            listed[key] = found
    return {goal: listed.get((goal, height), []) for goal in goals}

nonlinear_fold

nonlinear_fold(forest: DerivationForest, goal: Item, algebra: OrderPreservingSemiring, inputs: Mapping[InputId, Tensor], observe: Callable[[Derivation, Tensor], Tensor], *, limit: int, like: Tensor, height: int | None = None) -> Tensor

The sum over derivations of any function of a derivation and its weight.

No aggregate summarizes such a fold: with two derivations of weights -1 and 1, squaring gives 2 here and 0 on their sum. So every derivation is built, which the declared limit bounds.

PARAMETER DESCRIPTION
forest

The forest.

TYPE: DerivationForest

goal

The item.

TYPE: Item

algebra

The algebra of the weights and of the sum.

TYPE: OrderPreservingSemiring

inputs

The weights.

TYPE: Mapping of InputId to torch.Tensor

observe

The function of a derivation and its weight.

TYPE: Callable[[Derivation, Tensor], Tensor]

limit

The most derivations to build.

TYPE: int

like

The dtype and device of the zero.

TYPE: Tensor

height

The bound on height, required for a cyclic forest.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

The sum, zero when the goal has no derivation.

RAISES DESCRIPTION
ForestRefused

If the goal has more derivations than limit, or the forest has a cycle and no height is given.

Source code in src/quivers/stochastic/forest.py
def nonlinear_fold(
    forest: DerivationForest,
    goal: Item,
    algebra: OrderPreservingSemiring,
    inputs: Mapping[InputId, torch.Tensor],
    observe: Callable[[Derivation, torch.Tensor], torch.Tensor],
    *,
    limit: int,
    like: torch.Tensor,
    height: int | None = None,
) -> torch.Tensor:
    """The sum over derivations of any function of a derivation and its weight.

    No aggregate summarizes such a fold: with two derivations of weights
    ``-1`` and ``1``, squaring gives ``2`` here and ``0`` on their sum. So
    every derivation is built, which the declared limit bounds.

    Parameters
    ----------
    forest : DerivationForest
        The forest.
    goal : Item
        The item.
    algebra : OrderPreservingSemiring
        The algebra of the weights and of the sum.
    inputs : Mapping of InputId to torch.Tensor
        The weights.
    observe : Callable[[Derivation, torch.Tensor], torch.Tensor]
        The function of a derivation and its weight.
    limit : int
        The most derivations to build.
    like : torch.Tensor
        The dtype and device of the zero.
    height : int or None
        The bound on height, required for a cyclic forest.

    Returns
    -------
    torch.Tensor
        The sum, zero when the goal has no derivation.

    Raises
    ------
    ForestRefused
        If the goal has more derivations than ``limit``, or the forest
        has a cycle and no height is given.
    """
    terms = [
        (derivation, weight)
        for derivation, weight, _ in fold_derivations(
            forest,
            goal,
            algebra,
            inputs,
            _weights_only(forest),
            limit=limit,
            like=like,
            height=height,
        )
    ]
    total = algebra.zero_like((), like)
    for derivation, weight in terms:
        total = _join(algebra, total, observe(derivation, weight))
    return total

expected_embedding

expected_embedding(forest: DerivationForest, goal: Item, algebra: OrderPreservingSemiring, inputs: Mapping[InputId, Tensor], interpretation: HostInterpretation[Tensor], *, probability: Callable[[Tensor], Tensor], limit: int, like: Tensor, height: int | None = None) -> Tensor

The mean of a fold of the derivations into vectors, weighted by their weights.

sum_d p(d) phi(d) / sum_d p(d) with p(d) the derivation's weight read as a nonnegative real by probability (exp for log weights) and phi the interpretation's fold. A fold that is not linear, such as a neural encoder, has no aggregate over the forest, so the derivations are enumerated within the declared limit; each shared sub-derivation is folded once.

PARAMETER DESCRIPTION
forest

The forest.

TYPE: DerivationForest

goal

The item.

TYPE: Item

algebra

The algebra of the weights.

TYPE: OrderPreservingSemiring

inputs

The weights.

TYPE: Mapping of InputId to torch.Tensor

interpretation

The embedding of a derivation.

TYPE: HostInterpretation of torch.Tensor

probability

A derivation's weight as a nonnegative real.

TYPE: Callable[[Tensor], Tensor]

limit

The most derivations to build.

TYPE: int

like

The dtype and device of the unit.

TYPE: Tensor

height

The bound on height, required for a cyclic forest.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

The expected embedding.

RAISES DESCRIPTION
ForestRefused

If the goal has no derivation or more than limit, or the forest has a cycle and no height is given.

Source code in src/quivers/stochastic/forest.py
def expected_embedding(
    forest: DerivationForest,
    goal: Item,
    algebra: OrderPreservingSemiring,
    inputs: Mapping[InputId, torch.Tensor],
    interpretation: HostInterpretation[torch.Tensor],
    *,
    probability: Callable[[torch.Tensor], torch.Tensor],
    limit: int,
    like: torch.Tensor,
    height: int | None = None,
) -> torch.Tensor:
    """The mean of a fold of the derivations into vectors, weighted by their weights.

    ``sum_d p(d) phi(d) / sum_d p(d)`` with ``p(d)`` the derivation's
    weight read as a nonnegative real by ``probability`` (``exp`` for log
    weights) and ``phi`` the interpretation's fold. A fold that is not
    linear, such as a neural encoder, has no aggregate over the forest, so
    the derivations are enumerated within the declared limit; each shared
    sub-derivation is folded once.

    Parameters
    ----------
    forest : DerivationForest
        The forest.
    goal : Item
        The item.
    algebra : OrderPreservingSemiring
        The algebra of the weights.
    inputs : Mapping of InputId to torch.Tensor
        The weights.
    interpretation : HostInterpretation of torch.Tensor
        The embedding of a derivation.
    probability : Callable[[torch.Tensor], torch.Tensor]
        A derivation's weight as a nonnegative real.
    limit : int
        The most derivations to build.
    like : torch.Tensor
        The dtype and device of the unit.
    height : int or None
        The bound on height, required for a cyclic forest.

    Returns
    -------
    torch.Tensor
        The expected embedding.

    Raises
    ------
    ForestRefused
        If the goal has no derivation or more than ``limit``, or the
        forest has a cycle and no height is given.
    """
    listed = fold_derivations(
        forest,
        goal,
        algebra,
        inputs,
        interpretation,
        limit=limit,
        like=like,
        height=height,
    )
    if not listed:
        raise ForestRefused(ForestRefusal.MISSING, "the goal has no derivation")
    masses = torch.stack([probability(weight) for _, weight, _ in listed])
    embeddings = torch.stack([embedding for _, _, embedding in listed])
    shape = (len(listed),) + (1,) * (embeddings.dim() - 1)
    return (masses.reshape(shape) * embeddings).sum(0) / masses.sum()

encoder_interpretation

encoder_interpretation(encoder: Encoder, presentation: RulePresentation) -> HostInterpretation[Tensor]

The fold of an encoder over the derivations of its signature's presentation.

Each rule of presentation_of the encoder's signature is a constructor; its operation is the encoder's Encoder.step on the premises' embeddings and the node's values, interleaved by the kinds of the constructor's argument sorts. On every derivation it equals the encoder applied to the derivation's term.

PARAMETER DESCRIPTION
encoder

The encoder.

TYPE: Encoder

presentation

The presentation of the encoder's signature.

TYPE: RulePresentation

RETURNS DESCRIPTION
HostInterpretation of torch.Tensor

The fold.

RAISES DESCRIPTION
ValueError

If a rule or slot of the presentation is not a constructor of the signature.

Source code in src/quivers/stochastic/forest.py
def encoder_interpretation(
    encoder: Encoder, presentation: RulePresentation
) -> HostInterpretation[torch.Tensor]:
    """The fold of an encoder over the derivations of its signature's presentation.

    Each rule of `presentation_of` the encoder's signature is a
    constructor; its operation is the encoder's `Encoder.step` on the
    premises' embeddings and the node's values, interleaved by the kinds
    of the constructor's argument sorts. On every derivation it equals
    the encoder applied to the derivation's term.

    Parameters
    ----------
    encoder : Encoder
        The encoder.
    presentation : RulePresentation
        The presentation of the encoder's signature.

    Returns
    -------
    HostInterpretation of torch.Tensor
        The fold.

    Raises
    ------
    ValueError
        If a rule or slot of the presentation is not a constructor of the
        signature.
    """
    signature = encoder.signature
    operations: dict[ConstructorId, Callable[..., torch.Tensor]] = {}
    for identity, constructor in presentation.constructors_by_id.items():
        if constructor.name not in signature.constructors:
            raise ValueError(
                f"{constructor.name!r} is not a constructor of the signature"
            )
        operations[identity] = _step(encoder, signature, constructor.name)
    return HostInterpretation(presentation=presentation, operations=operations)