Skip to content

Deductive Systems, Rule Schemas, and Span Components

A chart parser stores partial conclusions and combines them with inference rules (Shieber et al., 1995; Goodman, 1999). In a categorial grammar, for instance, an expression that needs a noun phrase on its right combines with a noun phrase to give a sentence (Lambek, 1958). The interfaces below separate the initial facts, the inference steps, the goals, and the schedule, and the semiring fixes what is accumulated across derivations. The module holds the abstract deductive system, the rule schemas with their bundles and presets, and the components of CKY parsing over spans.

Deductive Systems

Five abstract primitives for weighted deductive parsing, of which the parsers in this package are instances:

  • Axiom: Creates and populates the initial chart from input.
  • Deduction: A weighted inference step (chart → chart).
  • Goal: Extracts the result from a completed chart.
  • Schedule: Evaluation strategy (CKY bottom-up, Earley, agenda-based).
  • DeductiveSystem: Ties axiom, deductions, goal, schedule, and semiring into a single nn.Module.

The deduction package exposes these primitives alongside fitting and sampling operations.

Rule Schemas

A rule schema is a function from a finite inventory of syntactic categories (CategorySystem) to a set of rules (RuleSystem). Each schema states one structural rule pattern, and its rules are the instances of that pattern over the inventory.

Schemas compose via | (union) and can carry default weights via .weighted(w). Grammar formalisms are specific compositions:

  • CCG = EVALUATION | HARMONIC_COMPOSITION | CROSSED_COMPOSITION
  • LAMBEK = EVALUATION | ADJUNCTION_UNITS | TENSOR_INTRODUCTION | TENSOR_PROJECTION
  • NL = EVALUATION
  • LP = EVALUATION | COMMUTATIVE_EVALUATION | ADJUNCTION_UNITS

About twenty atomic schemas, such as ForwardApplication and BackwardApplication, compose into twelve bundled schemas, such as EVALUATION and HARMONIC_COMPOSITION, which compose into the grammar presets CCG, LAMBEK, NL, and LP.

schema

Rule schemas: composable functors from CategorySystem to RuleSystem.

A RuleSchema is a functor that maps a CategorySystem to a RuleSystem. Schemas are the abstract building blocks of grammar formalisms: each schema defines a structural rule pattern, and concrete rule instances are generated by instantiating the pattern over a finite category inventory.

The two atomic schema types are:

  • BinaryRuleSchema: defined by a match predicate on category pairs: match(left, right) -> result | None.
  • UnaryRuleSchema: defined by a match predicate on single categories: match(cat, system) -> list[result].

Schemas compose via | (union) and can carry default weights via .weighted(w). Grammar formalisms are specific compositions::

CCG = EVALUATION | HARMONIC_COMPOSITION | CROSSED_COMPOSITION
LAMBEK = EVALUATION | ADJUNCTION_UNITS | TENSOR_INTRODUCTION | TENSOR_PROJECTION

The 13 bundled schemas (EVALUATION, HARMONIC_COMPOSITION, etc.) are themselves composed from ~20 atomic schemas (ForwardApplication, BackwardApplication, etc.), giving fine-grained control::

# only forward application, no backward
MY_GRAMMAR = ForwardApplication() | ForwardComposition()

RuleSchema

Bases: ABC

A functor CategorySystem -> RuleSystem.

Schemas are the abstract specification of structural rules. They compose via | (union) and + (alias for |).

weighted

weighted(weight: float) -> RuleSchema

Attach a default weight to all rules from this schema.

PARAMETER DESCRIPTION
weight

The weight every binary and unary rule receives.

TYPE: float

RETURNS DESCRIPTION
RuleSchema

A WeightedSchema wrapping this schema.

Source code in src/quivers/stochastic/schema.py
def weighted(self, weight: float) -> RuleSchema:
    """Attach a default weight to all rules from this schema.

    Parameters
    ----------
    weight : float
        The weight every binary and unary rule receives.

    Returns
    -------
    RuleSchema
        A `WeightedSchema` wrapping this schema.
    """
    return WeightedSchema(self, weight)

UnionSchema

UnionSchema(left: RuleSchema, right: RuleSchema)

Bases: RuleSchema

Union of two schemas (composes their rule systems via +).

PARAMETER DESCRIPTION
left

The first schema.

TYPE: RuleSchema

right

The second schema.

TYPE: RuleSchema

Source code in src/quivers/stochastic/schema.py
def __init__(self, left: RuleSchema, right: RuleSchema) -> None:
    self._left = left
    self._right = right

WeightedSchema

WeightedSchema(inner: RuleSchema, weight: float)

Bases: RuleSchema

Schema wrapper that attaches a default weight to all rules.

PARAMETER DESCRIPTION
inner

The schema whose rules are weighted.

TYPE: RuleSchema

weight

The weight every rule of inner receives.

TYPE: float

Source code in src/quivers/stochastic/schema.py
def __init__(self, inner: RuleSchema, weight: float) -> None:
    self._inner = inner
    self._weight = weight

BinaryRuleSchema

Bases: RuleSchema

Schema for binary rules, defined by a match predicate.

Subclasses implement match(left, right) -> result | None. The schema iterates over all category pairs and collects matches.

match abstractmethod

match(left: Category, right: Category) -> Category | None

Test whether (left, right) triggers this rule.

PARAMETER DESCRIPTION
left

Left antecedent.

TYPE: Category

right

Right antecedent.

TYPE: Category

RETURNS DESCRIPTION
Category or None

Result category if the pair matches, else None.

Source code in src/quivers/stochastic/schema.py
@abstractmethod
def match(
    self,
    left: Category,
    right: Category,
) -> Category | None:
    """Test whether (left, right) triggers this rule.

    Parameters
    ----------
    left : Category
        Left antecedent.
    right : Category
        Right antecedent.

    Returns
    -------
    Category or None
        Result category if the pair matches, else None.
    """
    ...

UnaryRuleSchema

Bases: RuleSchema

Schema for unary rules, defined by a match predicate.

Subclasses implement match(cat, system) -> list[result]. The schema iterates over all categories and collects matches.

match abstractmethod

match(cat: Category, system: CategorySystem) -> list[Category]

Find all valid results for a given input category.

PARAMETER DESCRIPTION
cat

Input category.

TYPE: Category

system

The full category inventory (needed for some schemas that must check existence of intermediate categories).

TYPE: CategorySystem

RETURNS DESCRIPTION
list[Category]

Valid result categories.

Source code in src/quivers/stochastic/schema.py
@abstractmethod
def match(
    self,
    cat: Category,
    system: CategorySystem,
) -> list[Category]:
    """Find all valid results for a given input category.

    Parameters
    ----------
    cat : Category
        Input category.
    system : CategorySystem
        The full category inventory (needed for some schemas
        that must check existence of intermediate categories).

    Returns
    -------
    list[Category]
        Valid result categories.
    """
    ...

ForwardApplication

Bases: BinaryRuleSchema

C/B ⊗ B → C (right evaluation / forward application).

match

match(left: Category, right: Category) -> Category | None

Return the conclusion this rule derives from a pair, if any.

PARAMETER DESCRIPTION
left

The left antecedent.

TYPE: Category

right

The right antecedent.

TYPE: Category

RETURNS DESCRIPTION
Category or None

The conclusion category, or None when the pair does not match this rule.

Source code in src/quivers/stochastic/schema.py
def match(self, left: Category, right: Category) -> Category | None:
    """Return the conclusion this rule derives from a pair, if any.

    Parameters
    ----------
    left : Category
        The left antecedent.
    right : Category
        The right antecedent.

    Returns
    -------
    Category or None
        The conclusion category, or ``None`` when the pair does
        not match this rule.
    """
    if (
        isinstance(left, SlashCategory)
        and left.direction == "/"
        and left.argument == right
    ):
        return left.result

    return None

BackwardApplication

Bases: BinaryRuleSchema

A ⊗ A\C → C (left evaluation / backward application).

match

match(left: Category, right: Category) -> Category | None

Return the conclusion this rule derives from a pair, if any.

PARAMETER DESCRIPTION
left

The left antecedent.

TYPE: Category

right

The right antecedent.

TYPE: Category

RETURNS DESCRIPTION
Category or None

The conclusion category, or None when the pair does not match this rule.

Source code in src/quivers/stochastic/schema.py
def match(self, left: Category, right: Category) -> Category | None:
    """Return the conclusion this rule derives from a pair, if any.

    Parameters
    ----------
    left : Category
        The left antecedent.
    right : Category
        The right antecedent.

    Returns
    -------
    Category or None
        The conclusion category, or ``None`` when the pair does
        not match this rule.
    """
    if (
        isinstance(right, SlashCategory)
        and right.direction == "\\"
        and right.argument == left
    ):
        return right.result

    return None

ForwardComposition

Bases: BinaryRuleSchema

C/B ⊗ B/A → C/A (right harmonic composition).

match

match(left: Category, right: Category) -> Category | None

Return the conclusion this rule derives from a pair, if any.

PARAMETER DESCRIPTION
left

The left antecedent.

TYPE: Category

right

The right antecedent.

TYPE: Category

RETURNS DESCRIPTION
Category or None

The conclusion category, or None when the pair does not match this rule.

Source code in src/quivers/stochastic/schema.py
def match(self, left: Category, right: Category) -> Category | None:
    """Return the conclusion this rule derives from a pair, if any.

    Parameters
    ----------
    left : Category
        The left antecedent.
    right : Category
        The right antecedent.

    Returns
    -------
    Category or None
        The conclusion category, or ``None`` when the pair does
        not match this rule.
    """
    if (
        isinstance(left, SlashCategory)
        and left.direction == "/"
        and isinstance(right, SlashCategory)
        and right.direction == "/"
        and left.argument == right.result
    ):
        return SlashCategory(
            result=left.result, argument=right.argument, direction="/"
        )

    return None

BackwardComposition

Bases: BinaryRuleSchema

A\B ⊗ B\C → A\C (left harmonic composition).

match

match(left: Category, right: Category) -> Category | None

Return the conclusion this rule derives from a pair, if any.

PARAMETER DESCRIPTION
left

The left antecedent.

TYPE: Category

right

The right antecedent.

TYPE: Category

RETURNS DESCRIPTION
Category or None

The conclusion category, or None when the pair does not match this rule.

Source code in src/quivers/stochastic/schema.py
def match(self, left: Category, right: Category) -> Category | None:
    """Return the conclusion this rule derives from a pair, if any.

    Parameters
    ----------
    left : Category
        The left antecedent.
    right : Category
        The right antecedent.

    Returns
    -------
    Category or None
        The conclusion category, or ``None`` when the pair does
        not match this rule.
    """
    if (
        isinstance(left, SlashCategory)
        and left.direction == "\\"
        and isinstance(right, SlashCategory)
        and right.direction == "\\"
        and right.argument == left.result
    ):
        return SlashCategory(
            result=right.result, argument=left.argument, direction="\\"
        )

    return None

ForwardCrossedComposition

Bases: BinaryRuleSchema

C/B ⊗ B\A → C\A (right-left crossed composition).

match

match(left: Category, right: Category) -> Category | None

Return the conclusion this rule derives from a pair, if any.

PARAMETER DESCRIPTION
left

The left antecedent.

TYPE: Category

right

The right antecedent.

TYPE: Category

RETURNS DESCRIPTION
Category or None

The conclusion category, or None when the pair does not match this rule.

Source code in src/quivers/stochastic/schema.py
def match(self, left: Category, right: Category) -> Category | None:
    """Return the conclusion this rule derives from a pair, if any.

    Parameters
    ----------
    left : Category
        The left antecedent.
    right : Category
        The right antecedent.

    Returns
    -------
    Category or None
        The conclusion category, or ``None`` when the pair does
        not match this rule.
    """
    if (
        isinstance(left, SlashCategory)
        and left.direction == "/"
        and isinstance(right, SlashCategory)
        and right.direction == "\\"
        and left.argument == right.result
    ):
        return SlashCategory(
            result=left.result, argument=right.argument, direction="\\"
        )

    return None

BackwardCrossedComposition

Bases: BinaryRuleSchema

A/B ⊗ B\C → A/C (left-right crossed composition).

match

match(left: Category, right: Category) -> Category | None

Return the conclusion this rule derives from a pair, if any.

PARAMETER DESCRIPTION
left

The left antecedent.

TYPE: Category

right

The right antecedent.

TYPE: Category

RETURNS DESCRIPTION
Category or None

The conclusion category, or None when the pair does not match this rule.

Source code in src/quivers/stochastic/schema.py
def match(self, left: Category, right: Category) -> Category | None:
    """Return the conclusion this rule derives from a pair, if any.

    Parameters
    ----------
    left : Category
        The left antecedent.
    right : Category
        The right antecedent.

    Returns
    -------
    Category or None
        The conclusion category, or ``None`` when the pair does
        not match this rule.
    """
    if (
        isinstance(left, SlashCategory)
        and left.direction == "/"
        and isinstance(right, SlashCategory)
        and right.direction == "\\"
        and right.argument == left.result
    ):
        return SlashCategory(
            result=right.result, argument=left.argument, direction="/"
        )

    return None

CommutativeForwardApplication

Bases: BinaryRuleSchema

B ⊗ C/B → C (commutative right evaluation).

match

match(left: Category, right: Category) -> Category | None

Return the conclusion this rule derives from a pair, if any.

PARAMETER DESCRIPTION
left

The left antecedent.

TYPE: Category

right

The right antecedent.

TYPE: Category

RETURNS DESCRIPTION
Category or None

The conclusion category, or None when the pair does not match this rule.

Source code in src/quivers/stochastic/schema.py
def match(self, left: Category, right: Category) -> Category | None:
    """Return the conclusion this rule derives from a pair, if any.

    Parameters
    ----------
    left : Category
        The left antecedent.
    right : Category
        The right antecedent.

    Returns
    -------
    Category or None
        The conclusion category, or ``None`` when the pair does
        not match this rule.
    """
    if (
        isinstance(right, SlashCategory)
        and right.direction == "/"
        and right.argument == left
    ):
        return right.result

    return None

CommutativeBackwardApplication

Bases: BinaryRuleSchema

A\C ⊗ A → C (commutative left evaluation).

match

match(left: Category, right: Category) -> Category | None

Return the conclusion this rule derives from a pair, if any.

PARAMETER DESCRIPTION
left

The left antecedent.

TYPE: Category

right

The right antecedent.

TYPE: Category

RETURNS DESCRIPTION
Category or None

The conclusion category, or None when the pair does not match this rule.

Source code in src/quivers/stochastic/schema.py
def match(self, left: Category, right: Category) -> Category | None:
    """Return the conclusion this rule derives from a pair, if any.

    Parameters
    ----------
    left : Category
        The left antecedent.
    right : Category
        The right antecedent.

    Returns
    -------
    Category or None
        The conclusion category, or ``None`` when the pair does
        not match this rule.
    """
    if (
        isinstance(left, SlashCategory)
        and left.direction == "\\"
        and left.argument == right
    ):
        return left.result

    return None

TensorIntroduction

Bases: BinaryRuleSchema

A ⊗ B → A⊗B (product formation).

match

match(left: Category, right: Category) -> Category | None

Return the conclusion this rule derives from a pair, if any.

PARAMETER DESCRIPTION
left

The left antecedent.

TYPE: Category

right

The right antecedent.

TYPE: Category

RETURNS DESCRIPTION
Category or None

The conclusion category, or None when the pair does not match this rule.

Source code in src/quivers/stochastic/schema.py
def match(self, left: Category, right: Category) -> Category | None:
    """Return the conclusion this rule derives from a pair, if any.

    Parameters
    ----------
    left : Category
        The left antecedent.
    right : Category
        The right antecedent.

    Returns
    -------
    Category or None
        The conclusion category, or ``None`` when the pair does
        not match this rule.
    """
    return ProductCategory(left=left, right=right)

LeftUnitElimination

Bases: BinaryRuleSchema

I ⊗ A → A (left unitor).

match

match(left: Category, right: Category) -> Category | None

Return the conclusion this rule derives from a pair, if any.

PARAMETER DESCRIPTION
left

The left antecedent.

TYPE: Category

right

The right antecedent.

TYPE: Category

RETURNS DESCRIPTION
Category or None

The conclusion category, or None when the pair does not match this rule.

Source code in src/quivers/stochastic/schema.py
def match(self, left: Category, right: Category) -> Category | None:
    """Return the conclusion this rule derives from a pair, if any.

    Parameters
    ----------
    left : Category
        The left antecedent.
    right : Category
        The right antecedent.

    Returns
    -------
    Category or None
        The conclusion category, or ``None`` when the pair does
        not match this rule.
    """
    if isinstance(left, UnitCategory):
        return right

    return None

RightUnitElimination

Bases: BinaryRuleSchema

A ⊗ I → A (right unitor).

match

match(left: Category, right: Category) -> Category | None

Return the conclusion this rule derives from a pair, if any.

PARAMETER DESCRIPTION
left

The left antecedent.

TYPE: Category

right

The right antecedent.

TYPE: Category

RETURNS DESCRIPTION
Category or None

The conclusion category, or None when the pair does not match this rule.

Source code in src/quivers/stochastic/schema.py
def match(self, left: Category, right: Category) -> Category | None:
    """Return the conclusion this rule derives from a pair, if any.

    Parameters
    ----------
    left : Category
        The left antecedent.
    right : Category
        The right antecedent.

    Returns
    -------
    Category or None
        The conclusion category, or ``None`` when the pair does
        not match this rule.
    """
    if isinstance(right, UnitCategory):
        return left

    return None

ModalApplication

ModalApplication(modality: str = '◇')

Bases: BinaryRuleSchema

◇(C/B) ⊗ ◇B → ◇C (modal function application).

PARAMETER DESCRIPTION
modality

The modality symbol (e.g. "◇", "□").

TYPE: str DEFAULT: '◇'

Source code in src/quivers/stochastic/schema.py
def __init__(self, modality: str = "◇") -> None:
    self._modality = modality

match

match(left: Category, right: Category) -> Category | None

Return the conclusion this rule derives from a pair, if any.

PARAMETER DESCRIPTION
left

The left antecedent.

TYPE: Category

right

The right antecedent.

TYPE: Category

RETURNS DESCRIPTION
Category or None

The conclusion category, or None when the pair does not match this rule.

Source code in src/quivers/stochastic/schema.py
def match(self, left: Category, right: Category) -> Category | None:
    """Return the conclusion this rule derives from a pair, if any.

    Parameters
    ----------
    left : Category
        The left antecedent.
    right : Category
        The right antecedent.

    Returns
    -------
    Category or None
        The conclusion category, or ``None`` when the pair does
        not match this rule.
    """
    if (
        not isinstance(left, ModalCategory)
        or left.modality != self._modality
        or not isinstance(right, ModalCategory)
        or right.modality != self._modality
    ):
        return None

    inner_left = left.inner
    inner_right = right.inner

    # ◇(C/B) ⊗ ◇B → ◇C
    if (
        isinstance(inner_left, SlashCategory)
        and inner_left.direction == "/"
        and inner_left.argument == inner_right
    ):
        return ModalCategory(modality=self._modality, inner=inner_left.result)

    # ◇A ⊗ ◇(A\C) → ◇C
    if (
        isinstance(inner_right, SlashCategory)
        and inner_right.direction == "\\"
        and inner_right.argument == inner_left
    ):
        return ModalCategory(modality=self._modality, inner=inner_right.result)

    return None

RightLifting

Bases: UnaryRuleSchema

A → C/(A\C) (right adjunction unit / type raising).

match

match(cat: Category, system: CategorySystem) -> list[Category]

Return the conclusions this rule derives from a category.

PARAMETER DESCRIPTION
cat

The antecedent category.

TYPE: Category

system

The category inventory; conclusions outside it are dropped.

TYPE: CategorySystem

RETURNS DESCRIPTION
list of Category

The conclusion categories, empty when the rule does not apply.

Source code in src/quivers/stochastic/schema.py
def match(self, cat: Category, system: CategorySystem) -> list[Category]:
    """Return the conclusions this rule derives from a category.

    Parameters
    ----------
    cat : Category
        The antecedent category.
    system : CategorySystem
        The category inventory; conclusions outside it are dropped.

    Returns
    -------
    list of Category
        The conclusion categories, empty when the rule does not
        apply.
    """
    results = []

    for c in system:
        inner = SlashCategory(result=c, argument=cat, direction="\\")

        if inner in system:
            raised = SlashCategory(result=c, argument=inner, direction="/")

            if raised in system:
                results.append(raised)

    return results

LeftLifting

Bases: UnaryRuleSchema

A → (C/A)\C (left adjunction unit / type raising).

match

match(cat: Category, system: CategorySystem) -> list[Category]

Return the conclusions this rule derives from a category.

PARAMETER DESCRIPTION
cat

The antecedent category.

TYPE: Category

system

The category inventory; conclusions outside it are dropped.

TYPE: CategorySystem

RETURNS DESCRIPTION
list of Category

The conclusion categories, empty when the rule does not apply.

Source code in src/quivers/stochastic/schema.py
def match(self, cat: Category, system: CategorySystem) -> list[Category]:
    """Return the conclusions this rule derives from a category.

    Parameters
    ----------
    cat : Category
        The antecedent category.
    system : CategorySystem
        The category inventory; conclusions outside it are dropped.

    Returns
    -------
    list of Category
        The conclusion categories, empty when the rule does not
        apply.
    """
    results = []

    for c in system:
        inner = SlashCategory(result=c, argument=cat, direction="/")

        if inner in system:
            raised = SlashCategory(result=c, argument=inner, direction="\\")

            if raised in system:
                results.append(raised)

    return results

LeftProjection

Bases: UnaryRuleSchema

A⊗B → A (left tensor projection).

match

match(cat: Category, system: CategorySystem) -> list[Category]

Return the conclusions this rule derives from a category.

PARAMETER DESCRIPTION
cat

The antecedent category.

TYPE: Category

system

The category inventory; conclusions outside it are dropped.

TYPE: CategorySystem

RETURNS DESCRIPTION
list of Category

The conclusion categories, empty when the rule does not apply.

Source code in src/quivers/stochastic/schema.py
def match(self, cat: Category, system: CategorySystem) -> list[Category]:
    """Return the conclusions this rule derives from a category.

    Parameters
    ----------
    cat : Category
        The antecedent category.
    system : CategorySystem
        The category inventory; conclusions outside it are dropped.

    Returns
    -------
    list of Category
        The conclusion categories, empty when the rule does not
        apply.
    """
    if isinstance(cat, ProductCategory) and cat.left in system:
        return [cat.left]

    return []

RightProjection

Bases: UnaryRuleSchema

A⊗B → B (right tensor projection).

match

match(cat: Category, system: CategorySystem) -> list[Category]

Return the conclusions this rule derives from a category.

PARAMETER DESCRIPTION
cat

The antecedent category.

TYPE: Category

system

The category inventory; conclusions outside it are dropped.

TYPE: CategorySystem

RETURNS DESCRIPTION
list of Category

The conclusion categories, empty when the rule does not apply.

Source code in src/quivers/stochastic/schema.py
def match(self, cat: Category, system: CategorySystem) -> list[Category]:
    """Return the conclusions this rule derives from a category.

    Parameters
    ----------
    cat : Category
        The antecedent category.
    system : CategorySystem
        The category inventory; conclusions outside it are dropped.

    Returns
    -------
    list of Category
        The conclusion categories, empty when the rule does not
        apply.
    """
    if isinstance(cat, ProductCategory) and cat.right in system:
        return [cat.right]

    return []

UnitCoercion

Bases: UnaryRuleSchema

A → I (unit elimination / weakening).

match

match(cat: Category, system: CategorySystem) -> list[Category]

Return the conclusions this rule derives from a category.

PARAMETER DESCRIPTION
cat

The antecedent category.

TYPE: Category

system

The category inventory; conclusions outside it are dropped.

TYPE: CategorySystem

RETURNS DESCRIPTION
list of Category

The conclusion categories, empty when the rule does not apply.

Source code in src/quivers/stochastic/schema.py
def match(self, cat: Category, system: CategorySystem) -> list[Category]:
    """Return the conclusions this rule derives from a category.

    Parameters
    ----------
    cat : Category
        The antecedent category.
    system : CategorySystem
        The category inventory; conclusions outside it are dropped.

    Returns
    -------
    list of Category
        The conclusion categories, empty when the rule does not
        apply.
    """
    unit = UnitCategory()

    if unit in system:
        return [unit]

    return []

ModalInjection

ModalInjection(modality: str = '◇')

Bases: UnaryRuleSchema

A → ◇A (modal introduction).

PARAMETER DESCRIPTION
modality

The modality symbol (e.g. "◇", "□").

TYPE: str DEFAULT: '◇'

Source code in src/quivers/stochastic/schema.py
def __init__(self, modality: str = "◇") -> None:
    self._modality = modality

match

match(cat: Category, system: CategorySystem) -> list[Category]

Return the conclusions this rule derives from a category.

PARAMETER DESCRIPTION
cat

The antecedent category.

TYPE: Category

system

The category inventory; conclusions outside it are dropped.

TYPE: CategorySystem

RETURNS DESCRIPTION
list of Category

The conclusion categories, empty when the rule does not apply.

Source code in src/quivers/stochastic/schema.py
def match(self, cat: Category, system: CategorySystem) -> list[Category]:
    """Return the conclusions this rule derives from a category.

    Parameters
    ----------
    cat : Category
        The antecedent category.
    system : CategorySystem
        The category inventory; conclusions outside it are dropped.

    Returns
    -------
    list of Category
        The conclusion categories, empty when the rule does not
        apply.
    """
    modal = ModalCategory(modality=self._modality, inner=cat)

    if modal in system:
        return [modal]

    return []

ModalProjection

ModalProjection(modality: str = '◇')

Bases: UnaryRuleSchema

◇A → A (modal elimination).

PARAMETER DESCRIPTION
modality

The modality symbol (e.g. "◇", "□").

TYPE: str DEFAULT: '◇'

Source code in src/quivers/stochastic/schema.py
def __init__(self, modality: str = "◇") -> None:
    self._modality = modality

match

match(cat: Category, system: CategorySystem) -> list[Category]

Return the conclusions this rule derives from a category.

PARAMETER DESCRIPTION
cat

The antecedent category.

TYPE: Category

system

The category inventory; conclusions outside it are dropped.

TYPE: CategorySystem

RETURNS DESCRIPTION
list of Category

The conclusion categories, empty when the rule does not apply.

Source code in src/quivers/stochastic/schema.py
def match(self, cat: Category, system: CategorySystem) -> list[Category]:
    """Return the conclusions this rule derives from a category.

    Parameters
    ----------
    cat : Category
        The antecedent category.
    system : CategorySystem
        The category inventory; conclusions outside it are dropped.

    Returns
    -------
    list of Category
        The conclusion categories, empty when the rule does not
        apply.
    """
    if (
        isinstance(cat, ModalCategory)
        and cat.modality == self._modality
        and cat.inner in system
    ):
        return [cat.inner]

    return []

GeneralizedComposition

GeneralizedComposition(max_depth: int = 2)

Bases: RuleSchema

Generalized composition through nested slashes (B^n).

C/B ⊗ (B|₁Z₁)|₂Z₂...|ₙZₙ → (C|₁Z₁)|₂Z₂...|ₙZₙ

This is a special schema because the match recurses into nested slash structure. At depth 1 it is ordinary harmonic composition; this schema only generates rules for depth >= 2.

PARAMETER DESCRIPTION
max_depth

Maximum nesting depth to traverse.

TYPE: int DEFAULT: 2

Source code in src/quivers/stochastic/schema.py
def __init__(self, max_depth: int = 2) -> None:
    self._max_depth = max_depth

PatternBinarySchema

PatternBinarySchema(left_pattern, right_pattern, conclusion_pattern, variables: frozenset[str], name: str = '')

Bases: BinaryRuleSchema

Binary rule schema from a DSL rule declaration.

Matches category pairs against two premise patterns and instantiates the conclusion pattern with bound variables.

PARAMETER DESCRIPTION
left_pattern

Category pattern for the left antecedent.

TYPE: ObjectExpr

right_pattern

Category pattern for the right antecedent.

TYPE: ObjectExpr

conclusion_pattern

Category pattern for the consequent.

TYPE: ObjectExpr

variables

Universally quantified pattern variables.

TYPE: frozenset of str

name

The rule's name (for description).

TYPE: str DEFAULT: ''

Source code in src/quivers/stochastic/schema.py
def __init__(
    self,
    left_pattern,
    right_pattern,
    conclusion_pattern,
    variables: frozenset[str],
    name: str = "",
) -> None:
    self._left = left_pattern
    self._right = right_pattern
    self._conclusion = conclusion_pattern
    self._variables = variables
    self._name = name

match

match(left: Category, right: Category) -> Category | None

Return the conclusion this rule derives from a pair, if any.

PARAMETER DESCRIPTION
left

The left antecedent.

TYPE: Category

right

The right antecedent.

TYPE: Category

RETURNS DESCRIPTION
Category or None

The conclusion category, or None when the pair does not match this rule.

Source code in src/quivers/stochastic/schema.py
def match(self, left: Category, right: Category) -> Category | None:
    """Return the conclusion this rule derives from a pair, if any.

    Parameters
    ----------
    left : Category
        The left antecedent.
    right : Category
        The right antecedent.

    Returns
    -------
    Category or None
        The conclusion category, or ``None`` when the pair does
        not match this rule.
    """
    bindings: dict[str, Category] = {}

    if not _match_pattern(self._left, left, bindings, self._variables):
        return None

    if not _match_pattern(self._right, right, bindings, self._variables):
        return None

    return _instantiate_pattern(
        self._conclusion,
        bindings,
        self._variables,
    )

PatternUnarySchema

PatternUnarySchema(premise_pattern, conclusion_pattern, variables: frozenset[str], name: str = '')

Bases: UnaryRuleSchema

Unary rule schema from a DSL rule declaration.

Matches a single category against a premise pattern and instantiates the conclusion pattern with bound variables.

PARAMETER DESCRIPTION
premise_pattern

Category pattern for the antecedent.

TYPE: ObjectExpr

conclusion_pattern

Category pattern for the consequent.

TYPE: ObjectExpr

variables

Universally quantified pattern variables.

TYPE: frozenset of str

name

The rule's name (for description).

TYPE: str DEFAULT: ''

Source code in src/quivers/stochastic/schema.py
def __init__(
    self,
    premise_pattern,
    conclusion_pattern,
    variables: frozenset[str],
    name: str = "",
) -> None:
    self._premise = premise_pattern
    self._conclusion = conclusion_pattern
    self._variables = variables
    self._name = name

match

match(cat: Category, system: CategorySystem) -> list[Category]

Return the conclusions this rule derives from a category.

PARAMETER DESCRIPTION
cat

The antecedent category.

TYPE: Category

system

The category inventory; conclusions outside it are dropped.

TYPE: CategorySystem

RETURNS DESCRIPTION
list of Category

The conclusion categories, empty when the rule does not apply.

Source code in src/quivers/stochastic/schema.py
def match(
    self,
    cat: Category,
    system: CategorySystem,
) -> list[Category]:
    """Return the conclusions this rule derives from a category.

    Parameters
    ----------
    cat : Category
        The antecedent category.
    system : CategorySystem
        The category inventory; conclusions outside it are dropped.

    Returns
    -------
    list of Category
        The conclusion categories, empty when the rule does not
        apply.
    """
    if self._modal_endpoints is not None:
        name, premise, conclusion = self._modal_endpoints
        modality = system._modal_patterns.get(name)
        if modality is not None and premise is not None and conclusion is not None:
            if cat != ModalCategory(modality=modality, inner=premise):
                return []
            result = ModalCategory(modality=modality, inner=conclusion)
            return [result] if result in system else []
    bindings: dict[str, Category] = {}

    if not _match_pattern(self._premise, cat, bindings, self._variables):
        return []

    result = _instantiate_pattern(
        self._conclusion,
        bindings,
        self._variables,
    )

    if result is None:
        return []

    return [result]

generalized_composition

generalized_composition(max_depth: int = 2) -> RuleSchema

Create a generalized composition schema.

PARAMETER DESCRIPTION
max_depth

Maximum nesting depth.

TYPE: int DEFAULT: 2

RETURNS DESCRIPTION
RuleSchema

The generalized composition schema.

Source code in src/quivers/stochastic/schema.py
def generalized_composition(max_depth: int = 2) -> RuleSchema:
    """Create a generalized composition schema.

    Parameters
    ----------
    max_depth : int
        Maximum nesting depth.

    Returns
    -------
    RuleSchema
        The generalized composition schema.
    """
    return GeneralizedComposition(max_depth)

schema_presentation

schema_presentation(schema: RuleSchema, system: CategorySystem, name: str) -> RulePresentation

The rule presentation of a schema instantiated over categories.

Each category is a constructor of one closed sort; the judgment span(c, i, j) says that category c covers the input from i to j. A ground binary rule result -> left right is the rule span(left, i, k), span(right, k, j) |- span(result, i, j) and a ground unary rule result -> input is span(input, i, j) |- span(result, i, j), each in the order the schema generates them; a lexical entry is an occurrence of the word slot, which carries its word.

PARAMETER DESCRIPTION
schema

The schema.

TYPE: RuleSchema

system

The categories it is instantiated over.

TYPE: CategorySystem

name

The presentation's name.

TYPE: str

RETURNS DESCRIPTION
RulePresentation

The presentation; a rule's weight parameter is named by its position among the rules of its arity.

Source code in src/quivers/stochastic/schema.py
def schema_presentation(
    schema: RuleSchema, system: CategorySystem, name: str
) -> RulePresentation:
    """The rule presentation of a schema instantiated over categories.

    Each category is a constructor of one closed sort; the judgment
    ``span(c, i, j)`` says that category ``c`` covers the input from
    ``i`` to ``j``. A ground binary rule ``result -> left right`` is the
    rule ``span(left, i, k), span(right, k, j) |- span(result, i, j)`` and
    a ground unary rule ``result -> input`` is
    ``span(input, i, j) |- span(result, i, j)``, each in the order the
    schema generates them; a lexical entry is an occurrence of the
    ``word`` slot, which carries its word.

    Parameters
    ----------
    schema : RuleSchema
        The schema.
    system : CategorySystem
        The categories it is instantiated over.
    name : str
        The presentation's name.

    Returns
    -------
    RulePresentation
        The presentation; a rule's weight parameter is named by its
        position among the rules of its arity.
    """
    rules = schema(system)
    labels = tuple(str(category) for category in system)
    sort = UserIndexSort(name="Category", constructors=labels)
    span = FamilyId.derive(name, "judgment", "span")

    def judgment(category: str | IndexVariable, start: str, end: str) -> Judgment:
        """A span judgment.

        Parameters
        ----------
        category : str or IndexVariable
            A category label, or a variable over categories.
        start, end : str
            The position variables.

        Returns
        -------
        Judgment
            The judgment.
        """
        label = (
            category
            if isinstance(category, IndexVariable)
            else IndexLiteral(value=category, sort=sort)
        )
        return Judgment(
            family=span,
            arguments=(
                label,
                IndexVariable(name=start, sort=NAT),
                IndexVariable(name=end, sort=NAT),
            ),
        )

    binary = tuple(IndexBinder(name=item, sort=NAT) for item in ("i", "k", "j"))
    unary = tuple(IndexBinder(name=item, sort=NAT) for item in ("i", "j"))
    presented: list[Rule] = []
    for index, (result, left, right) in enumerate(rules.binary_rules):
        presented.append(
            Rule(
                id=ConstructorId.derive(name, "binary", index),
                name=f"binary{index}",
                telescope=binary,
                premises=(
                    Premise(judgment=judgment(labels[left], "i", "k")),
                    Premise(judgment=judgment(labels[right], "k", "j")),
                ),
                conclusion=judgment(labels[result], "i", "j"),
                weight=ParameterId.derive(name, "binary", index),
            )
        )
    for index, (result, source) in enumerate(rules.unary_rules):
        presented.append(
            Rule(
                id=ConstructorId.derive(name, "unary", index),
                name=f"unary{index}",
                telescope=unary,
                premises=(Premise(judgment=judgment(labels[source], "i", "j")),),
                conclusion=judgment(labels[result], "i", "j"),
                weight=ParameterId.derive(name, "unary", index),
            )
        )
    category = IndexVariable(name="c", sort=sort)
    return RulePresentation(
        id=PresentationId.derive(name),
        name=name,
        index_sorts=(sort,),
        judgments=(
            JudgmentDecl(
                id=span,
                name="span",
                indices=(
                    IndexBinder(name="c", sort=sort, refinable=True),
                    IndexBinder(name="i", sort=NAT, refinable=True),
                    IndexBinder(name="j", sort=NAT, refinable=True),
                ),
            ),
        ),
        rules=tuple(presented),
        axioms=(
            AxiomSlot(
                id=ConstructorId.derive(name, "word"),
                name="word",
                telescope=(IndexBinder(name="c", sort=sort), *unary),
                judgment=judgment(category, "i", "j"),
                values=(FieldDef(name="word", type=STRING),),
            ),
        ),
    )

Bundled schemas

Stochastic morphisms: Markov kernels over finite sets.

This module provides the probabilistic layer for quivers, implementing the category FinStoch of finite sets and stochastic maps (Markov kernels). This is the Kleisli category of the Giry monad restricted to finite sets, where:

  • Objects are finite sets (same as the base category).
  • Morphisms A -> B are stochastic matrices: tensors of shape (|A|, |B|) whose rows sum to 1.
  • Composition is standard matrix multiplication.
  • Identity is the Kronecker delta.

The package also re-exports MarkovAlgebra and its singleton MARKOV from quivers.core.algebras, the algebra these morphisms compose under.

Submodules

morphisms : StochasticMorphism, CategoricalMorphism families : Discretized distribution families transforms : condition, mix, factor, normalize queries : prob, marginal_prob, expectation giry : GiryMonad, FinStoch categories : Category types including atoms, slashes, products, unit, modals semiring : Chart semiring abstractions (LogProb, Viterbi, Boolean, Counting) schema : Composable rule schemas (functors CategorySystem -> RuleSystem) rules : Rule systems and the CCG / Lambek presets span : Span-based CKY components (LexicalAxiom, BinarySpanDeduction, etc.) parsers, ccg, lambek : Chart parsers inside : The inside algorithm over a rule system agenda : The agenda-driven weighted-deduction engine indexed : Charts indexed on the argument positions rule joins look up joins : Worst-case optimal joins and variable elimination for rule bodies planning : Plans for queries over rule presentations forest : Packed forests of derivations and folds over them recursion : Linear cyclic systems solved through the algebra's closure tries : Tries of relations and the intersection step of Generic Join productions : A grammar's productions grouped by left-hand side effect_lifts : Effect-lifted rule schemas for deduction systems deduction : Abstract weighted deductive system framework and its operations stdlib : Pre-registered deduction systems

EVALUATION module-attribute

Forward and backward application, the evaluation maps of a biclosed category.

HARMONIC_COMPOSITION module-attribute

HARMONIC_COMPOSITION = ForwardComposition() | BackwardComposition()

Forward and backward harmonic composition.

CROSSED_COMPOSITION module-attribute

Forward and backward crossed composition.

COMMUTATIVE_EVALUATION module-attribute

Application with the argument on either side, for commutative (LP) grammars.

ADJUNCTION_UNITS module-attribute

ADJUNCTION_UNITS = RightLifting() | LeftLifting()

Right and left type raising, the units of the slash adjunctions.

TENSOR_INTRODUCTION module-attribute

TENSOR_INTRODUCTION = TensorIntroduction()

Product formation, A, B -> A*B.

TENSOR_PROJECTION module-attribute

TENSOR_PROJECTION = LeftProjection() | RightProjection()

Left and right projections out of a product category.

UNIT_INTRODUCTION module-attribute

UNIT_INTRODUCTION = LeftUnitElimination() | RightUnitElimination()

The left and right unitors, I*A -> A and A*I -> A.

UNIT_ELIMINATION module-attribute

UNIT_ELIMINATION = UnitCoercion()

Coercion of any category to the monoidal unit, A -> I.

MODAL_INTRODUCTION module-attribute

MODAL_INTRODUCTION = ModalInjection()

Modal injection, A -> <>A.

MODAL_ELIMINATION module-attribute

MODAL_ELIMINATION = ModalProjection()

Modal projection, <>A -> A.

MODAL_APPLICATION module-attribute

MODAL_APPLICATION = ModalApplication()

Function application under a modality.

Grammar presets and the schema registry

Stochastic morphisms: Markov kernels over finite sets.

This module provides the probabilistic layer for quivers, implementing the category FinStoch of finite sets and stochastic maps (Markov kernels). This is the Kleisli category of the Giry monad restricted to finite sets, where:

  • Objects are finite sets (same as the base category).
  • Morphisms A -> B are stochastic matrices: tensors of shape (|A|, |B|) whose rows sum to 1.
  • Composition is standard matrix multiplication.
  • Identity is the Kronecker delta.

The package also re-exports MarkovAlgebra and its singleton MARKOV from quivers.core.algebras, the algebra these morphisms compose under.

Submodules

morphisms : StochasticMorphism, CategoricalMorphism families : Discretized distribution families transforms : condition, mix, factor, normalize queries : prob, marginal_prob, expectation giry : GiryMonad, FinStoch categories : Category types including atoms, slashes, products, unit, modals semiring : Chart semiring abstractions (LogProb, Viterbi, Boolean, Counting) schema : Composable rule schemas (functors CategorySystem -> RuleSystem) rules : Rule systems and the CCG / Lambek presets span : Span-based CKY components (LexicalAxiom, BinarySpanDeduction, etc.) parsers, ccg, lambek : Chart parsers inside : The inside algorithm over a rule system agenda : The agenda-driven weighted-deduction engine indexed : Charts indexed on the argument positions rule joins look up joins : Worst-case optimal joins and variable elimination for rule bodies planning : Plans for queries over rule presentations forest : Packed forests of derivations and folds over them recursion : Linear cyclic systems solved through the algebra's closure tries : Tries of relations and the intersection step of Generic Join productions : A grammar's productions grouped by left-hand side effect_lifts : Effect-lifted rule schemas for deduction systems deduction : Abstract weighted deductive system framework and its operations stdlib : Pre-registered deduction systems

CCG module-attribute

The combinatory categorial grammar preset: application plus harmonic and crossed composition.

LAMBEK module-attribute

The Lambek calculus preset: application, type raising, and the product rules.

NL module-attribute

The non-associative Lambek calculus preset: application only.

LP module-attribute

The Lambek calculus with permutation preset: application in both orders and type raising.

SCHEMA_REGISTRY module-attribute

SCHEMA_REGISTRY: dict[str, RuleSchema] = {'evaluation': EVALUATION, 'harmonic_composition': HARMONIC_COMPOSITION, 'crossed_composition': CROSSED_COMPOSITION, 'generalized_composition': GeneralizedComposition(), 'adjunction_units': ADJUNCTION_UNITS, 'tensor_introduction': TENSOR_INTRODUCTION, 'tensor_projection': TENSOR_PROJECTION, 'commutative_evaluation': COMMUTATIVE_EVALUATION, 'unit_introduction': UNIT_INTRODUCTION, 'unit_elimination': UNIT_ELIMINATION, 'modal_introduction': MODAL_INTRODUCTION, 'modal_elimination': MODAL_ELIMINATION, 'modal_application': MODAL_APPLICATION}

The bundled schemas by the name a DSL rules clause uses for each.

CKY Components over Spans

Instantiation over spans of the abstract deductive framework for CKY chart parsing:

  • LexicalAxiom: Populates length-1 spans from a learnable lexicon.
  • BinarySpanDeduction: Applies binary structural rules with learnable weights.
  • UnarySpanDeduction: Applies unary rules to convergence.
  • SpanGoal: Extracts the score of the start symbol over the full span.
  • CKYSchedule: Bottom-up evaluation by span length.

span

Span-based CKY components for the deductive system framework.

This module instantiates the abstract deduction primitives (Axiom, Deduction, Goal, Schedule) for span-indexed chart parsing (CKY). Items are indexed by (i, j, A) where [i, j) is a string span and A is a category index.

The chart tensor has shape (batch, n_categories, seq_len, seq_len+1) (categories-first for efficient indexing of the start symbol).

Components

LexicalAxiom Populates length-1 spans from a learnable lexicon. BinarySpanDeduction Applies binary rules: chart[i,k,L] ⊗ chart[k,j,R] → chart[i,j,A]. UnarySpanDeduction Closes a cell under the unary rules by their Kleene star. SpanGoal Extracts chart[start_cat, 0, seq_len]. CKYSchedule Bottom-up evaluation by span length.

Span plans

span_grammar reads the span form of a rule presentation, and span_inside and span_recognize are the executors that quivers.stochastic.planning.plan selects for it: values by length, with the split points of each premise pair summed before the rules, and support by Boolean matrix products over the split points.

Edge

Edge = tuple[int, int, Tensor]

A weighted step between categories over one span: from, to, weight.

LexicalAxiom

LexicalAxiom(n_terminals: int, n_categories: int)

Bases: Axiom

Populate length-1 spans from a learnable lexicon.

Creates the chart tensor and fills chart[b, :, i, i+1] = log_softmax(lexicon[tokens[b, i]]).

PARAMETER DESCRIPTION
n_terminals

Vocabulary size.

TYPE: int

n_categories

Number of category types.

TYPE: int

Source code in src/quivers/stochastic/span.py
def __init__(self, n_terminals: int, n_categories: int) -> None:
    super().__init__()
    self._n_cat = n_categories
    self.lexicon_logits = nn.Parameter(torch.randn(n_terminals, n_categories) * 0.1)

log_lexicon property

log_lexicon: Tensor

The log-probability lexicon.

RETURNS DESCRIPTION
Tensor

Shape (n_terminals, n_categories).

forward

forward(tokens: Tensor, semiring: ChartSemiring) -> SpanChart

Fill the length-1 spans from the lexicon.

PARAMETER DESCRIPTION
tokens

Integer terminal indices of shape (batch, seq_len).

TYPE: Tensor

semiring

The scoring semiring, recorded on the chart.

TYPE: ChartSemiring

RETURNS DESCRIPTION
SpanChart

A chart whose cells (i, i + 1) hold the lexical log-probabilities of each token.

Source code in src/quivers/stochastic/span.py
def forward(self, tokens: torch.Tensor, semiring: ChartSemiring) -> SpanChart:  # type: ignore[override]
    """Fill the length-1 spans from the lexicon.

    Parameters
    ----------
    tokens : torch.Tensor
        Integer terminal indices of shape ``(batch, seq_len)``.
    semiring : ChartSemiring
        The scoring semiring, recorded on the chart.

    Returns
    -------
    SpanChart
        A chart whose cells ``(i, i + 1)`` hold the lexical
        log-probabilities of each token.
    """
    batch, seq_len = tokens.shape
    log_lex = self.log_lexicon[tokens]  # (batch, seq_len, C)

    # build chart as list-of-lists (functional, no in-place writes)
    # stored as flat dict keyed by (i, j)
    chart_cells: dict[tuple[int, int], torch.Tensor] = {}

    for i in range(seq_len):
        chart_cells[(i, i + 1)] = log_lex[:, i, :]  # (batch, C)

    # pack into metadata for the schedule
    return SpanChart(
        cells=chart_cells,
        batch=batch,
        seq_len=seq_len,
        n_categories=self._n_cat,
        device=tokens.device,
        semiring=semiring,
    )

SpanChart

SpanChart(cells: dict[tuple[int, int], Tensor], batch: int, seq_len: int, n_categories: int, device: device, semiring: ChartSemiring)

A span-indexed chart held as functional (non-in-place) cells.

This wraps a dict of (i, j) -> (batch, C) tensors. The schedule fills cells bottom-up, and to_tensor() assembles them into a dense (batch, C, seq_len, seq_len+1) tensor.

PARAMETER DESCRIPTION
cells

The filled cells, keyed by span (i, j), each of shape (batch, n_categories).

TYPE: dict of (int, int) to torch.Tensor

batch

The batch size.

TYPE: int

seq_len

The sentence length.

TYPE: int

n_categories

The number of categories.

TYPE: int

device

The device the dense chart is built on.

TYPE: device

semiring

The scoring semiring; its zero fills unfilled cells.

TYPE: ChartSemiring

Source code in src/quivers/stochastic/span.py
def __init__(
    self,
    cells: dict[tuple[int, int], torch.Tensor],
    batch: int,
    seq_len: int,
    n_categories: int,
    device: torch.device,
    semiring: ChartSemiring,
) -> None:
    self.cells = cells
    self.batch = batch
    self.seq_len = seq_len
    self.n_categories = n_categories
    self.device = device
    self.semiring = semiring

to_tensor

to_tensor() -> Tensor

Assemble cells into a dense chart tensor.

RETURNS DESCRIPTION
Tensor

Shape (batch, n_categories, seq_len, seq_len+1).

Source code in src/quivers/stochastic/span.py
def to_tensor(self) -> torch.Tensor:
    """Assemble cells into a dense chart tensor.

    Returns
    -------
    torch.Tensor
        Shape ``(batch, n_categories, seq_len, seq_len+1)``.
    """
    like = next(iter(self.cells.values()), torch.empty(0, device=self.device))
    chart = self.semiring.zero_like(
        (self.batch, self.n_categories, self.seq_len, self.seq_len + 1), like
    )

    for (i, j), cell in self.cells.items():
        chart[:, :, i, j] = cell

    return chart

BinarySpanDeduction

BinarySpanDeduction(rule_system: RuleSystem, learnable: bool = True)

Bases: Deduction

Binary rule application over span items.

For each split point k in [i+1, j), combines chart[i, k, lefts] and chart[k, j, rights] to produce chart[i, j, results].

PARAMETER DESCRIPTION
rule_system

The structural rules.

TYPE: RuleSystem

learnable

Whether rule weights are learnable.

TYPE: bool DEFAULT: True

Source code in src/quivers/stochastic/span.py
def __init__(
    self,
    rule_system: RuleSystem,
    learnable: bool = True,
) -> None:
    super().__init__()

    results, lefts, rights = rule_system.binary_tensors()
    self.register_buffer("_results", results)
    self.register_buffer("_lefts", lefts)
    self.register_buffer("_rights", rights)
    self._n_rules = rule_system.n_binary

    weights = rule_system.binary_weight_tensor()

    if learnable and self._n_rules > 0:
        self.weights = nn.Parameter(weights)

    else:
        self.register_buffer("weights", weights)

forward

forward(chart: Tensor | None, semiring: ChartSemiring, **context) -> Tensor

Apply binary rules for one span cell (i, j).

PARAMETER DESCRIPTION
chart

Unused; the cells are read from chart_cells.

TYPE: Tensor or None

semiring

The scoring semiring.

TYPE: ChartSemiring

**context

i and j (the span bounds), chart_cells (the filled cells keyed by span), and n_categories.

DEFAULT: {}

RETURNS DESCRIPTION
Tensor

The (batch, C) scores for cell (i, j), aggregated over every split point.

Source code in src/quivers/stochastic/span.py
def forward(
    self,
    chart: torch.Tensor | None,
    semiring: ChartSemiring,
    **context,
) -> torch.Tensor:
    """Apply binary rules for one span cell (i, j).

    Parameters
    ----------
    chart : torch.Tensor or None
        Unused; the cells are read from ``chart_cells``.
    semiring : ChartSemiring
        The scoring semiring.
    **context
        ``i`` and ``j`` (the span bounds), ``chart_cells`` (the
        filled cells keyed by span), and ``n_categories``.

    Returns
    -------
    torch.Tensor
        The ``(batch, C)`` scores for cell ``(i, j)``, aggregated
        over every split point.
    """
    i = context["i"]
    j = context["j"]
    chart_cells = context["chart_cells"]
    n_categories = context["n_categories"]

    _results = cast(torch.Tensor, self._results)
    _lefts = cast(torch.Tensor, self._lefts)
    _rights = cast(torch.Tensor, self._rights)

    if self._n_rules == 0:
        return torch.full(
            (chart_cells[(i, i + 1)].shape[0], n_categories),
            semiring.zero,
            device=_results.device,
        )

    parts = []

    for k in range(i + 1, j):
        left_cell = chart_cells[(i, k)]
        right_cell = chart_cells[(k, j)]

        left_scores = left_cell[:, _lefts]
        right_scores = right_cell[:, _rights]
        combined = semiring.times(left_scores, right_scores)

        if self._n_rules > 0:
            combined = semiring.times(
                combined,
                self.weights.unsqueeze(0),
            )

        parts.append(combined)

    stacked = torch.stack(parts, dim=0)
    split_scores = semiring.plus(stacked, dim=0)

    fibers: list[list[int]] = [[] for _ in range(n_categories)]
    for position, result in enumerate(_results.tolist()):
        fibers[result].append(position)
    return fiber_join(
        semiring,
        split_scores,
        fibers,
        semiring.zero_like((split_scores.shape[0], 1), split_scores),
    )

UnarySpanDeduction

UnarySpanDeduction(rule_system: RuleSystem, learnable: bool = True)

Bases: Deduction

Unary rules over one span, closed under their Kleene star.

A unary rule (a, b) with weight w derives category a over a span from category b over the same span. Chains of such rules never consume input and may cycle, so a cell is closed once by the closure U* = I ⊕ U ⊕ U² ⊕ ... of the rule matrix U[b, a] = ⊕ w, which sums every chain exactly once Stolcke (1995), section 4.5.2, generalized to a semiring as in Goodman (1999).

PARAMETER DESCRIPTION
rule_system

The structural rules.

TYPE: RuleSystem

learnable

Whether rule weights are learnable.

TYPE: bool DEFAULT: True

Source code in src/quivers/stochastic/span.py
def __init__(
    self,
    rule_system: RuleSystem,
    learnable: bool = True,
) -> None:
    super().__init__()

    unary = rule_system.unary_tensors()

    if unary is not None:
        self.register_buffer("_results", unary[0])
        self.register_buffer("_inputs", unary[1])

    else:
        self.register_buffer(
            "_results",
            torch.zeros(0, dtype=torch.long),
        )
        self.register_buffer(
            "_inputs",
            torch.zeros(0, dtype=torch.long),
        )

    self._n_rules = rule_system.n_unary

    weights = rule_system.unary_weight_tensor()

    if learnable and self._n_rules > 0:
        self.weights = nn.Parameter(weights)

    else:
        self.register_buffer("weights", weights)

has_rules property

has_rules: bool

Whether this deduction has any unary rules.

RETURNS DESCRIPTION
bool

True when it has one.

rule_matrix

rule_matrix(n_categories: int, semiring: ChartSemiring) -> Tensor

The unary rules as a matrix over the semiring.

PARAMETER DESCRIPTION
n_categories

The number of categories C.

TYPE: int

semiring

The scoring semiring.

TYPE: ChartSemiring

RETURNS DESCRIPTION
Tensor

(C, C): entry [b, a] is the semiring sum of the weights of the rules deriving a from b, and the semiring's zero where there is none.

Source code in src/quivers/stochastic/span.py
def rule_matrix(self, n_categories: int, semiring: ChartSemiring) -> torch.Tensor:
    """The unary rules as a matrix over the semiring.

    Parameters
    ----------
    n_categories : int
        The number of categories ``C``.
    semiring : ChartSemiring
        The scoring semiring.

    Returns
    -------
    torch.Tensor
        ``(C, C)``: entry ``[b, a]`` is the semiring sum of the
        weights of the rules deriving ``a`` from ``b``, and the
        semiring's zero where there is none.
    """
    _results = cast(torch.Tensor, self._results)
    _inputs = cast(torch.Tensor, self._inputs)
    weights = cast(torch.Tensor, self.weights)
    flat = _inputs * n_categories + _results
    one_hot = torch.full(
        (self._n_rules, n_categories * n_categories),
        float(semiring.zero),
        dtype=weights.dtype,
        device=weights.device,
    )
    placed = one_hot.scatter(1, flat.unsqueeze(1), weights.unsqueeze(1))
    return semiring.plus(placed, dim=0).reshape(n_categories, n_categories)

closure

closure(n_categories: int, semiring: ChartSemiring) -> Tensor

The Kleene star U* of the unary-rule matrix.

PARAMETER DESCRIPTION
n_categories

The number of categories C.

TYPE: int

semiring

The scoring semiring.

TYPE: ChartSemiring

RETURNS DESCRIPTION
Tensor

(C, C): entry [b, a] is the semiring sum, over the chains of unary rules deriving a from b (the empty chain included), of the product of their weights.

RAISES DESCRIPTION
DivergentClosureError

If the closure's series diverges in the semiring.

Source code in src/quivers/stochastic/span.py
def closure(self, n_categories: int, semiring: ChartSemiring) -> torch.Tensor:
    """The Kleene star ``U*`` of the unary-rule matrix.

    Parameters
    ----------
    n_categories : int
        The number of categories ``C``.
    semiring : ChartSemiring
        The scoring semiring.

    Returns
    -------
    torch.Tensor
        ``(C, C)``: entry ``[b, a]`` is the semiring sum, over the
        chains of unary rules deriving ``a`` from ``b`` (the empty
        chain included), of the product of their weights.

    Raises
    ------
    DivergentClosureError
        If the closure's series diverges in the semiring.
    """
    return kleene_star(self.rule_matrix(n_categories, semiring), semiring)

forward

forward(chart: Tensor, semiring: ChartSemiring, **context) -> Tensor

Close a cell under the unary rules.

PARAMETER DESCRIPTION
chart

A (batch, C) cell tensor.

TYPE: Tensor

semiring

The scoring semiring.

TYPE: ChartSemiring

**context

closure: a precomputed closure to reuse across the cells of one parse; computed here when absent.

DEFAULT: {}

RETURNS DESCRIPTION
Tensor

The (batch, C) cell chart ⊗ U*.

RAISES DESCRIPTION
DivergentClosureError

If the closure's series diverges in the semiring.

Source code in src/quivers/stochastic/span.py
def forward(
    self,
    chart: torch.Tensor,
    semiring: ChartSemiring,
    **context,
) -> torch.Tensor:
    """Close a cell under the unary rules.

    Parameters
    ----------
    chart : torch.Tensor
        A ``(batch, C)`` cell tensor.
    semiring : ChartSemiring
        The scoring semiring.
    **context
        ``closure``: a precomputed `closure` to reuse across the
        cells of one parse; computed here when absent.

    Returns
    -------
    torch.Tensor
        The ``(batch, C)`` cell ``chart ⊗ U*``.

    Raises
    ------
    DivergentClosureError
        If the closure's series diverges in the semiring.
    """
    if not self.has_rules:
        return chart
    star = context.get("closure")
    if not isinstance(star, torch.Tensor):
        star = self.closure(chart.shape[1], semiring)
    return apply_star(chart, star, semiring)

SpanGoal

SpanGoal(start_idx: int)

Bases: Goal

Extract chart[start_cat, 0, seq_len].

PARAMETER DESCRIPTION
start_idx

Index of the start category.

TYPE: int

Source code in src/quivers/stochastic/span.py
def __init__(self, start_idx: int) -> None:
    super().__init__()
    self._start_idx = start_idx

forward

forward(chart: Tensor) -> Tensor

Read the start category's score over the whole sentence.

PARAMETER DESCRIPTION
chart

The dense chart of shape (batch, C, seq_len, seq_len+1).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The (batch,) scores at chart[:, start, 0, seq_len].

Source code in src/quivers/stochastic/span.py
def forward(self, chart: torch.Tensor) -> torch.Tensor:
    """Read the start category's score over the whole sentence.

    Parameters
    ----------
    chart : torch.Tensor
        The dense chart of shape ``(batch, C, seq_len, seq_len+1)``.

    Returns
    -------
    torch.Tensor
        The ``(batch,)`` scores at ``chart[:, start, 0, seq_len]``.
    """
    seq_len = chart.shape[2]
    return chart[:, self._start_idx, 0, seq_len]

CKYSchedule

Bases: Schedule

Bottom-up CKY: process spans in increasing length order.

For each span length 2..n: 1. Apply binary deductions for each cell (i, i+span_len). 2. Apply unary deductions to the resulting cell.

run

run(chart: SpanChart, deductions: ModuleList, semiring: ChartSemiring) -> Tensor

Fill the chart bottom-up and return it as a dense tensor.

PARAMETER DESCRIPTION
chart

The chart LexicalAxiom produced, with its length-1 cells filled.

TYPE: SpanChart

deductions

The BinarySpanDeduction and UnarySpanDeduction steps; other deductions are ignored.

TYPE: ModuleList

semiring

The scoring semiring.

TYPE: ChartSemiring

RETURNS DESCRIPTION
Tensor

The dense chart of shape (batch, C, seq_len, seq_len+1).

Source code in src/quivers/stochastic/span.py
def run(  # type: ignore[override]
    self,
    chart: SpanChart,
    deductions: nn.ModuleList,
    semiring: ChartSemiring,
) -> torch.Tensor:
    """Fill the chart bottom-up and return it as a dense tensor.

    Parameters
    ----------
    chart : SpanChart
        The chart `LexicalAxiom` produced, with its length-1
        cells filled.
    deductions : nn.ModuleList
        The `BinarySpanDeduction` and `UnarySpanDeduction`
        steps; other deductions are ignored.
    semiring : ChartSemiring
        The scoring semiring.

    Returns
    -------
    torch.Tensor
        The dense chart of shape ``(batch, C, seq_len, seq_len+1)``.
    """
    span_chart = chart
    cells = span_chart.cells
    seq_len = span_chart.seq_len
    n_categories = span_chart.n_categories

    # separate binary and unary deductions
    binary_deds = [d for d in deductions if isinstance(d, BinarySpanDeduction)]
    unary_deds = [d for d in deductions if isinstance(d, UnarySpanDeduction)]

    # each unary deduction's closure is computed once per parse
    closures = {
        id(ud): ud.closure(n_categories, semiring)
        for ud in unary_deds
        if ud.has_rules
    }

    # apply unary rules to lexical cells first
    for i in range(seq_len):
        cell = cells[(i, i + 1)]

        for ud in unary_deds:
            if ud.has_rules:
                cell = ud(cell, semiring, closure=closures[id(ud)])

        cells[(i, i + 1)] = cell

    # fill chart bottom-up
    for span_len in range(2, seq_len + 1):
        for i in range(seq_len - span_len + 1):
            j = i + span_len

            # binary step: accumulate across all binary deductions
            cell = None

            for bd in binary_deds:
                contrib = bd(
                    None,
                    semiring,
                    i=i,
                    j=j,
                    chart_cells=cells,
                    n_categories=n_categories,
                )

                if cell is None:
                    cell = contrib

                else:
                    cell = semiring.plus_pair(cell, contrib)

            if cell is None:
                cell = torch.full(
                    (span_chart.batch, n_categories),
                    semiring.zero,
                    device=span_chart.device,
                )

            # unary step
            for ud in unary_deds:
                if ud.has_rules:
                    cell = ud(cell, semiring, closure=closures[id(ud)])

            cells[(i, j)] = cell

    # assemble into dense tensor
    return span_chart.to_tensor()

SpanRefused

SpanRefused(reason: str, code: Literal['form', 'cycle', 'nonlinear', 'sides', 'algebra'] = 'form')

Bases: ValueError

A presentation is not in span form, or a run does not fit its plan.

PARAMETER DESCRIPTION
reason

Why.

TYPE: str

code

"form" when the presentation is not in span form; for a run, "cycle" when its cells form a cycle the contract does not admit, "nonlinear" when nullable items form a nonlinear cycle, "sides" when a cycle multiplies on both sides of a product that does not commute, and "algebra" when a cycle needs a star the algebra lacks.

TYPE: str DEFAULT: 'form'

Source code in src/quivers/stochastic/span.py
def __init__(
    self,
    reason: str,
    code: Literal["form", "cycle", "nonlinear", "sides", "algebra"] = "form",
) -> None:
    super().__init__(reason)
    self.reason = reason
    self.code = code

SpanRule didactic-model

SpanRule(*, rule: Rule = field(opaque=True, extras=OPAQUE_BY_VALUE), binding: dict[str, Ground] = field(opaque=True, extras=OPAQUE_BY_VALUE), result: int, left: int = -1, right: int = -1, reads: Literal['none', 'span', 'split'] = 'none', positions: tuple[str, ...] = ())

Bases: ValueModel

One instance of a rule over categories, as the span kernel reads it.

PARAMETER DESCRIPTION
rule

The rule.

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

binding

The values of its category variables.

TYPE: dict of str to Ground DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

result

The conclusion's category.

TYPE: int

left

The first premise's category; -1 for a rule without premises.

TYPE: int DEFAULT: -1

right

The second premise's category; -1 for a rule with fewer than two.

TYPE: int DEFAULT: -1

reads

What positions the side condition reads: "none", "span" (the conclusion's ends only), or "split" (the split point too).

TYPE: str DEFAULT: 'none'

positions

The rule's position variables: start and end, with the split point between them for a binary rule.

TYPE: tuple of str DEFAULT: ()

SpanGrammar didactic-model

SpanGrammar(*, presentation: RulePresentation = field(opaque=True, extras=OPAQUE_BY_VALUE), family: FamilyId = field(opaque=True, extras=OPAQUE_BY_VALUE), category_slots: tuple[int, ...] = (), start: int = 0, end: int = 1, categories: tuple[tuple[str, ...], ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), binary: tuple[SpanRule, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), unary: tuple[SpanRule, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), constants: tuple[SpanRule, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), unary_cyclic: bool = False)

Bases: ValueModel

A presentation in span form: categories over spans of positions.

Every judgment is of one family whose indices are some indices of closed sorts of nullary constructors, the category, and two natural numbers, the start and end of a span. Every rule is binary, A(i, j) <- B(i, k), C(k, j), unary, A(i, j) <- B(i, j), or has no premises and a ground conclusion; its position arguments are variables, its category arguments literals or variables of their sorts (a variable stands for each constructor in turn), and its side condition may read any of them. The length j - i grows strictly along a binary rule, so the spans of each length are final once the shorter ones are; that is the schedule.

PARAMETER DESCRIPTION
presentation

The presentation.

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

family

The family.

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

category_slots

The argument positions of the category.

TYPE: tuple of int DEFAULT: ()

start

The argument position of the start.

TYPE: int DEFAULT: 0

end

The argument position of the end.

TYPE: int DEFAULT: 1

categories

Every category, its constructors at the category slots in order.

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

binary

The binary rule instances.

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

unary

The unary rule instances.

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

constants

The rules without premises.

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

unary_cyclic

Whether the unary rules' graph of categories has a cycle.

TYPE: bool DEFAULT: False

pairs property

pairs: tuple[tuple[int, int, int], ...]

The distinct premise pairs of the binary rules.

A rule whose side condition reads the split point is a pair of its own, since its sum over split points is its own.

RETURNS DESCRIPTION
tuple of tuple of int

(left, right, own): the categories and the rule's position in binary when it is a pair of its own, else -1.

category

category(item: Item) -> int

The category of an item of the family.

PARAMETER DESCRIPTION
item

The item.

TYPE: Item

RETURNS DESCRIPTION
int

Its category's position in categories.

Source code in src/quivers/stochastic/span.py
def category(self, item: Item) -> int:
    """The category of an item of the family.

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

    Returns
    -------
    int
        Its category's position in `categories`.
    """
    key = tuple(str(item.arguments[slot]) for slot in self.category_slots)
    return self.categories.index(key)

positions

positions(item: Item) -> tuple[int, int]

The start and end of an item of the family.

PARAMETER DESCRIPTION
item

The item.

TYPE: Item

RETURNS DESCRIPTION
tuple of int

(i, j).

Source code in src/quivers/stochastic/span.py
def positions(self, item: Item) -> tuple[int, int]:
    """The start and end of an item of the family.

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

    Returns
    -------
    tuple of int
        ``(i, j)``.
    """
    start, end = item.arguments[self.start], item.arguments[self.end]
    assert isinstance(start, int) and isinstance(end, int)
    return start, end

item

item(category: int, start: int, end: int) -> Item

The item of a category over a span.

PARAMETER DESCRIPTION
category

The category's position.

TYPE: int

start

The start.

TYPE: int

end

The end.

TYPE: int

RETURNS DESCRIPTION
Item

The item.

Source code in src/quivers/stochastic/span.py
def item(self, category: int, start: int, end: int) -> Item:
    """The item of a category over a span.

    Parameters
    ----------
    category : int
        The category's position.
    start : int
        The start.
    end : int
        The end.

    Returns
    -------
    Item
        The item.
    """
    width = len(self.category_slots) + 2
    arguments: list[Ground] = [0] * width
    for slot, value in zip(
        self.category_slots, self.categories[category], strict=True
    ):
        arguments[slot] = value
    arguments[self.start] = start
    arguments[self.end] = end
    return Item(family=self.family, arguments=tuple(arguments))

SpanWork didactic-model

SpanWork(*, products: int = 0, sums: int = 0, pivots: int = 0, exact: int = 0, conditions: int = 0, allocated: int = 0, peak: int = 0)

Bases: ValueModel

The work of a span run, in elements of the algebra.

PARAMETER DESCRIPTION
products

Binary products.

TYPE: int DEFAULT: 0

sums

Binary sums.

TYPE: int DEFAULT: 0

pivots

Closures of one element inside the unary closures.

TYPE: int DEFAULT: 0

exact

Operations of the closures' exact decisions.

TYPE: int DEFAULT: 0

conditions

Side conditions evaluated.

TYPE: int DEFAULT: 0

allocated

Elements of the tensors formed.

TYPE: int DEFAULT: 0

peak

Elements formed and held at once: the chart so far and one length's temporaries.

TYPE: int DEFAULT: 0

span_grammar

span_grammar(presentation: RulePresentation) -> SpanGrammar

The span form of a presentation.

PARAMETER DESCRIPTION
presentation

The presentation.

TYPE: RulePresentation

RETURNS DESCRIPTION
SpanGrammar

Its span form.

RAISES DESCRIPTION
TypeError

If it is not a rule presentation.

SpanRefused

If the presentation is not in span form, with the first reason.

Source code in src/quivers/stochastic/span.py
def span_grammar(presentation: RulePresentation) -> SpanGrammar:
    """The span form of a presentation.

    Parameters
    ----------
    presentation : RulePresentation
        The presentation.

    Returns
    -------
    SpanGrammar
        Its span form.

    Raises
    ------
    TypeError
        If it is not a rule presentation.
    SpanRefused
        If the presentation is not in span form, with the first reason.
    """
    if not isinstance(presentation, RulePresentation):
        raise TypeError(
            f"span form is read from a rule presentation, not a "
            f"{type(presentation).__name__}"
        )
    if len(presentation.judgments) != 1:
        raise SpanRefused("span form has one judgment family")
    (declaration,) = presentation.judgments
    naturals = [
        index for index, binder in enumerate(declaration.indices) if binder.sort == NAT
    ]
    if len(naturals) != 2:
        raise SpanRefused(
            "span form has two natural-number indices, a start and an end"
        )
    sorts: list[UserIndexSort] = []
    slots: list[int] = []
    for index, binder in enumerate(declaration.indices):
        if index in naturals:
            continue
        sort = binder.sort
        if not isinstance(sort, UserIndexSort) or any(sort.arities):
            raise SpanRefused(
                f"index {binder.name!r} is not of a closed sort of nullary constructors"
            )
        sorts.append(sort)
        slots.append(index)
    start, end = naturals
    categories = tuple(itertools.product(*(sort.constructors for sort in sorts)))
    family = declaration.id
    binary: list[SpanRule] = []
    unary: list[SpanRule] = []
    constants: list[SpanRule] = []

    def assignments(rule: Rule) -> list[dict[str, Ground]]:
        """Every assignment of the rule's category variables.

        Parameters
        ----------
        rule : Rule
            The rule.

        Returns
        -------
        list of dict of str to Ground
            The assignments.

        Raises
        ------
        SpanRefused
            If a category is neither a constant nor a variable.
        """
        names: dict[str, UserIndexSort] = {}
        for judgment in (rule.conclusion, *(p.judgment for p in rule.premises)):
            for slot, sort in zip(slots, sorts, strict=True):
                argument = judgment.arguments[slot]
                if isinstance(argument, IndexVariable):
                    names.setdefault(argument.name, sort)
                elif not isinstance(argument, IndexLiteral):
                    raise SpanRefused(
                        f"{rule.name}: a category is neither a constant nor a variable"
                    )
        keys = list(names)
        return [
            dict(zip(keys, values, strict=True))
            for values in itertools.product(*(names[key].constructors for key in keys))
        ]

    def category_of(judgment: Judgment, binding: Mapping[str, Ground]) -> int:
        """The category of a pattern under an assignment.

        Parameters
        ----------
        judgment : Judgment
            The pattern.
        binding : Mapping of str to Ground
            The category variables' values.

        Returns
        -------
        int
            The category's position.
        """
        key = tuple(
            str(evaluate_index(judgment.arguments[slot], binding)) for slot in slots
        )
        return categories.index(key)

    for rule in presentation.rules:
        judgments = (rule.conclusion, *(premise.judgment for premise in rule.premises))
        if any(judgment.family != family for judgment in judgments):
            raise SpanRefused(f"{rule.name}: a judgment of another family")
        if any(premise.hypotheses for premise in rule.premises):
            raise SpanRefused(f"{rule.name}: a premise has hypotheses")
        reads_positions: set[str] = set()
        if not rule.premises:
            conclusion = rule.conclusion
            if not all(
                isinstance(conclusion.arguments[slot], IndexLiteral)
                for slot in (start, end)
            ):
                raise SpanRefused(f"{rule.name}: a rule without premises is not ground")
            for binding in assignments(rule):
                constants.append(
                    SpanRule(
                        rule=rule,
                        binding=binding,
                        result=category_of(conclusion, binding),
                    )
                )
            continue
        spans = [_positions_of(judgment, start, end) for judgment in judgments]
        if any(span is None for span in spans):
            raise SpanRefused(f"{rule.name}: a position is not a variable")
        conclusion_span, *premise_spans = [span for span in spans if span is not None]
        condition = rule.side_condition
        arguments = set() if condition is None else set(condition.arguments)
        if len(premise_spans) == 1:
            if (
                premise_spans[0] != conclusion_span
                or conclusion_span[0] == conclusion_span[1]
            ):
                raise SpanRefused(f"{rule.name}: a unary rule changes its span")
            reads_positions = arguments & set(conclusion_span)
            kind = "span" if reads_positions else "none"
            for binding in assignments(rule):
                unary.append(
                    SpanRule(
                        rule=rule,
                        binding=binding,
                        result=category_of(rule.conclusion, binding),
                        left=category_of(rule.premises[0].judgment, binding),
                        reads=kind,
                        positions=conclusion_span,
                    )
                )
            continue
        if len(premise_spans) != 2:
            raise SpanRefused(f"{rule.name}: span form has at most two premises")
        (i, k), (k2, j) = premise_spans
        if k != k2 or conclusion_span != (i, j) or len({i, k, j}) != 3:
            raise SpanRefused(
                f"{rule.name}: a binary rule is not A(i, j) <- B(i, k), C(k, j)"
            )
        kind = "split" if k in arguments else "span" if arguments & {i, j} else "none"
        for binding in assignments(rule):
            binary.append(
                SpanRule(
                    rule=rule,
                    binding=binding,
                    result=category_of(rule.conclusion, binding),
                    left=category_of(rule.premises[0].judgment, binding),
                    right=category_of(rule.premises[1].judgment, binding),
                    reads=kind,
                    positions=(i, k, j),
                )
            )
    for slot in presentation.axioms:
        if slot.judgment.family != family:
            raise SpanRefused(f"input {slot.name} is of another family")
    edges: dict[int, set[int]] = {}
    for rule in unary:
        edges.setdefault(rule.left, set()).add(rule.result)
    return SpanGrammar(
        presentation=presentation,
        family=family,
        category_slots=tuple(slots),
        start=start,
        end=end,
        categories=categories,
        binary=tuple(binary),
        unary=tuple(unary),
        constants=tuple(constants),
        unary_cyclic=_cyclic(edges),
    )

span_inside

span_inside(grammar: SpanGrammar, algebra: OrderPreservingSemiring, seeds: Mapping[int, Tensor], length: int, binary: list[Tensor], unary: list[Tensor], *, like: Tensor, empty: Sequence[set[int]] = (), cyclic: bool = False) -> tuple[dict[int, Tensor], SpanWork]

The inside values of every span, by span length.

For each length l from one to the input's, the cells of length l are computed at once: for each distinct premise pair (B, C) the products x(B, i, k) ⊗ x(C, k, i + l) are summed over the split points k first, then each binary rule multiplies its pair's sum by its weight, the rules are summed into their conclusion's category, the inputs of the length are added, and the cells are closed under the unary rules. Summing the split points before the rules is right distributivity, so the products keep the premises' order and the rule weight last, and no product over categories, rules and split points together is formed.

Inputs over empty spans make categories nullable. Their weights over each empty span are solved first (_nullable), and a binary rule with an empty premise becomes a step of its cell over one span, closed with the unary rules: the standard treatment of empty spans, exact.

PARAMETER DESCRIPTION
grammar

The grammar.

TYPE: SpanGrammar

algebra

The algebra.

TYPE: OrderPreservingSemiring

seeds

For each length, (n - l + 1, N, *element_shape): the inputs and constants over each span of that length, the zero elsewhere; a length without inputs is absent.

TYPE: Mapping of int to torch.Tensor

length

n, the last position.

TYPE: int

binary

The weight of each instance of SpanGrammar.binary.

TYPE: list of torch.Tensor

unary

The weight of each instance of SpanGrammar.unary.

TYPE: list of torch.Tensor

like

The dtype and device.

TYPE: Tensor

empty

The categories of the inputs over each empty span, by position; none by default. Their weights are seeds[0].

TYPE: Sequence of set of int DEFAULT: ()

cyclic

Whether the contract admits a cycle over one span.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
tuple of dict and SpanWork

For each length l, the cells (n - l + 1, N, *element_shape) starting at 0 .. n - l, the empty spans at length zero when some input is over one; and the work.

RAISES DESCRIPTION
SpanRefused

If the steps over one span have a cycle the contract does not admit or the algebra cannot sum, nullable categories form a nonlinear cycle, or an empty first premise needs a commutative product the algebra does not establish.

Source code in src/quivers/stochastic/span.py
def span_inside(
    grammar: SpanGrammar,
    algebra: OrderPreservingSemiring,
    seeds: Mapping[int, torch.Tensor],
    length: int,
    binary: list[torch.Tensor],
    unary: list[torch.Tensor],
    *,
    like: torch.Tensor,
    empty: Sequence[set[int]] = (),
    cyclic: bool = False,
) -> tuple[dict[int, torch.Tensor], SpanWork]:
    """The inside values of every span, by span length.

    For each length ``l`` from one to the input's, the cells of length
    ``l`` are computed at once: for each distinct premise pair ``(B, C)``
    the products ``x(B, i, k) ⊗ x(C, k, i + l)`` are summed over the split
    points ``k`` first, then each binary rule multiplies its pair's sum by
    its weight, the rules are summed into their conclusion's category,
    the inputs of the length are added, and the cells are closed under the
    unary rules. Summing the split points before the rules is right
    distributivity, so the products keep the premises' order and the
    rule weight last, and no product over categories, rules and split
    points together is formed.

    Inputs over empty spans make categories nullable. Their weights over
    each empty span are solved first (`_nullable`), and a binary rule with
    an empty premise becomes a step of its cell over one span, closed with
    the unary rules: the standard treatment of empty spans, exact.

    Parameters
    ----------
    grammar : SpanGrammar
        The grammar.
    algebra : OrderPreservingSemiring
        The algebra.
    seeds : Mapping of int to torch.Tensor
        For each length, ``(n - l + 1, N, *element_shape)``: the inputs and
        constants over each span of that length, the zero elsewhere; a
        length without inputs is absent.
    length : int
        ``n``, the last position.
    binary : list of torch.Tensor
        The weight of each instance of `SpanGrammar.binary`.
    unary : list of torch.Tensor
        The weight of each instance of `SpanGrammar.unary`.
    like : torch.Tensor
        The dtype and device.
    empty : Sequence of set of int
        The categories of the inputs over each empty span, by position;
        none by default. Their weights are ``seeds[0]``.
    cyclic : bool
        Whether the contract admits a cycle over one span.

    Returns
    -------
    tuple of dict and SpanWork
        For each length ``l``, the cells ``(n - l + 1, N, *element_shape)``
        starting at ``0 .. n - l``, the empty spans at length zero when
        some input is over one; and the work.

    Raises
    ------
    SpanRefused
        If the steps over one span have a cycle the contract does not
        admit or the algebra cannot sum, nullable categories form a
        nonlinear cycle, or an empty first premise needs a commutative
        product the algebra does not establish.
    """
    rank = len(algebra.element_shape)
    count = _Count(rank)
    size = len(grammar.categories)
    pairs = grammar.pairs
    pair_of = {pair: position for position, pair in enumerate(pairs)}
    rule_pair = [
        pair_of[(rule.left, rule.right, position if rule.reads == "split" else -1)]
        for position, rule in enumerate(grammar.binary)
    ]
    fibers: list[list[int]] = [[] for _ in range(size)]
    for position, rule in enumerate(grammar.binary):
        fibers[rule.result].append(position)
    lefts = torch.tensor([pair[0] for pair in pairs], dtype=torch.long)
    rights = torch.tensor([pair[1] for pair in pairs], dtype=torch.long)
    weights = torch.stack(binary) if binary else None
    closures: dict[tuple[bool, ...], torch.Tensor] = {}
    chart: dict[int, torch.Tensor] = {}
    support = [
        _support(
            grammar,
            set(empty[position]) if position < len(empty) else set(),
            position,
            [True] * len(grammar.binary),
            [True] * len(grammar.unary),
            count,
        )
        for position in range(length + 1)
    ]
    nullable = any(support)
    if nullable:
        initial = seeds.get(0)
        chart[0] = _nullable(
            grammar,
            algebra,
            initial
            if initial is not None
            else algebra.zero_like((length + 1, size), like),
            support,
            binary,
            unary,
            like,
            count,
            cyclic,
        )
        count.held += count.elements(chart[0])
    for width in range(1, length + 1):
        rows = length - width + 1
        cells = seeds.get(width)
        if cells is None:
            cells = count.made(algebra.zero_like((rows, size), like))
        if width > 1 and pairs and weights is not None:
            left = count.made(
                torch.stack([chart[k][:rows] for k in range(1, width)], dim=1)
            )
            right = count.made(
                torch.stack(
                    [chart[width - k][k : k + rows] for k in range(1, width)], dim=1
                )
            )
            products = count.times(
                algebra,
                left.index_select(2, lefts.to(left.device)),
                right.index_select(2, rights.to(right.device)),
            )
            own = [position for position, pair in enumerate(pairs) if pair[2] >= 0]
            if own:
                mask = torch.ones(
                    (rows, width - 1, len(pairs)), dtype=torch.bool, device=like.device
                )
                for position in own:
                    rule = grammar.binary[pairs[position][2]]
                    for start in range(rows):
                        for split in range(1, width):
                            mask[start, split - 1, position] = _holds(
                                grammar,
                                rule,
                                (start, start + split, start + width),
                                count,
                            )
                shaped = mask.reshape(*mask.shape, *([1] * rank))
                products = torch.where(
                    shaped, products, algebra.zero_like(tuple(products.shape[:3]), like)
                )
            summed = count.plus(algebra, products, 1)
            gathered = summed.index_select(
                1, torch.tensor(rule_pair, dtype=torch.long, device=like.device)
            )
            weighted = count.times(algebra, gathered, weights.unsqueeze(0))
            spans = [
                position
                for position, rule in enumerate(grammar.binary)
                if rule.reads == "span"
            ]
            if spans:
                mask = torch.ones(
                    (rows, len(grammar.binary)), dtype=torch.bool, device=like.device
                )
                for position in spans:
                    for start in range(rows):
                        mask[start, position] = _holds(
                            grammar,
                            grammar.binary[position],
                            (start, start + width),
                            count,
                        )
                shaped = mask.reshape(*mask.shape, *([1] * rank))
                weighted = torch.where(
                    shaped, weighted, algebra.zero_like(tuple(weighted.shape[:2]), like)
                )
            derived = count.made(
                fiber_join(
                    algebra,
                    weighted,
                    fibers,
                    algebra.zero_like((rows, 1), like),
                    axis=1,
                )
            )
            widest = max((len(fiber) for fiber in fibers), default=0)
            count.sums += rows * size * max(widest - 1, 0)
            cells = count.made(algebra.join_pair(cells, derived))
            count.sums += rows * size
            count.temporary = 0
        extra: dict[int, list[Edge]] = {}
        if nullable:
            for start in range(rows):
                if support[start] or support[start + width]:
                    found = _empty_steps(
                        grammar,
                        algebra,
                        chart[0],
                        support,
                        binary,
                        start,
                        start + width,
                        count,
                    )
                    if found:
                        extra[start] = found
        closed = _unary_closure(
            grammar, algebra, cells, width, unary, like, count, closures, extra, cyclic
        )
        chart[width] = closed
        count.held += count.elements(closed)
        count.temporary = 0
    return chart, count.report()

span_recognize

span_recognize(grammar: SpanGrammar, seeds: Mapping[int, Tensor], length: int, binary: list[bool], unary: list[bool], *, device: device, empty: Sequence[set[int]] = ()) -> tuple[dict[int, Tensor], SpanWork]

Which category is derivable over which span, by Boolean matrix products.

For each length the pair matrix M[i][B, C] = OR_k x(B, i, k) AND x(C, k, i + l) is the product of two 0-1 matrices over the split points, computed as one batched matrix product and read as > 0; each present binary rule reads its pair, and the cells are closed under the present unary rules by one product with their closure. The products are of counts below 2^53, so float64 holds them exactly.

PARAMETER DESCRIPTION
grammar

The grammar.

TYPE: SpanGrammar

seeds

For each length, (n - l + 1, N) Booleans: the inputs present.

TYPE: Mapping of int to torch.Tensor

length

n.

TYPE: int

binary

Whether each binary instance is present.

TYPE: list of bool

unary

Whether each unary instance is present.

TYPE: list of bool

device

The device.

TYPE: device

empty

The categories of the inputs present over each empty span.

TYPE: Sequence of set of int DEFAULT: ()

RETURNS DESCRIPTION
tuple of dict and SpanWork

For each length, (n - l + 1, N) Booleans, the empty spans at length zero; and the work, a matrix product of sizes a b c counted as a b c products.

Source code in src/quivers/stochastic/span.py
def span_recognize(
    grammar: SpanGrammar,
    seeds: Mapping[int, torch.Tensor],
    length: int,
    binary: list[bool],
    unary: list[bool],
    *,
    device: torch.device,
    empty: Sequence[set[int]] = (),
) -> tuple[dict[int, torch.Tensor], SpanWork]:
    """Which category is derivable over which span, by Boolean matrix products.

    For each length the pair matrix ``M[i][B, C] = OR_k x(B, i, k) AND
    x(C, k, i + l)`` is the product of two 0-1 matrices over the split
    points, computed as one batched matrix product and read as ``> 0``;
    each present binary rule reads its pair, and the cells are closed
    under the present unary rules by one product with their closure.
    The products are of counts below ``2^53``, so float64 holds them
    exactly.

    Parameters
    ----------
    grammar : SpanGrammar
        The grammar.
    seeds : Mapping of int to torch.Tensor
        For each length, ``(n - l + 1, N)`` Booleans: the inputs present.
    length : int
        ``n``.
    binary : list of bool
        Whether each binary instance is present.
    unary : list of bool
        Whether each unary instance is present.
    device : torch.device
        The device.
    empty : Sequence of set of int
        The categories of the inputs present over each empty span.

    Returns
    -------
    tuple of dict and SpanWork
        For each length, ``(n - l + 1, N)`` Booleans, the empty spans at
        length zero; and the work, a matrix product of sizes ``a b c``
        counted as ``a b c`` products.
    """
    count = _Count(0)
    size = len(grammar.categories)
    chart: dict[int, torch.Tensor] = {}
    closures: dict[tuple[tuple[int, int], ...], torch.Tensor] = {}
    conditioned = [
        position for position, rule in enumerate(grammar.unary) if rule.reads != "none"
    ]
    present = [rule for rule, kept in zip(grammar.binary, binary, strict=True) if kept]
    support = [
        _support(
            grammar,
            set(empty[position]) if position < len(empty) else set(),
            position,
            binary,
            unary,
            count,
        )
        for position in range(length + 1)
    ]
    if any(support):
        reached = torch.zeros((length + 1, size), dtype=torch.float64, device=device)
        for position, categories in enumerate(support):
            for category in categories:
                reached[position, category] = 1.0
        chart[0] = reached
    for width in range(1, length + 1):
        rows = length - width + 1
        cells = seeds.get(width)
        cells = (
            torch.zeros((rows, size), dtype=torch.float64, device=device)
            if cells is None
            else cells.to(torch.float64)
        )
        if width > 1 and present:
            left = torch.stack([chart[k][:rows] for k in range(1, width)], dim=1)
            right = torch.stack(
                [chart[width - k][k : k + rows] for k in range(1, width)], dim=1
            )
            pairs = torch.bmm(left.transpose(1, 2), right) > 0
            count.products += rows * size * size * (width - 1)
            derived = torch.zeros((rows, size), dtype=torch.float64, device=device)
            for rule in present:
                if rule.reads == "split":
                    hit = torch.tensor(
                        [
                            any(
                                bool(left[start, split - 1, rule.left])
                                and bool(right[start, split - 1, rule.right])
                                and _holds(
                                    grammar,
                                    rule,
                                    (start, start + split, start + width),
                                    count,
                                )
                                for split in range(1, width)
                            )
                            for start in range(rows)
                        ],
                        dtype=torch.bool,
                        device=device,
                    )
                else:
                    hit = pairs[:, rule.left, rule.right]
                if rule.reads == "span":
                    hit = hit & torch.tensor(
                        [
                            _holds(grammar, rule, (start, start + width), count)
                            for start in range(rows)
                        ],
                        dtype=torch.bool,
                        device=device,
                    )
                derived[:, rule.result] = torch.maximum(
                    derived[:, rule.result], hit.to(torch.float64)
                )
                count.sums += rows
            cells = torch.maximum(cells, derived)
        if grammar.unary or any(support):
            closed = cells.clone()
            for start in range(rows):
                end = start + width
                edges = [
                    (rule.left, rule.result)
                    for position, rule in enumerate(grammar.unary)
                    if unary[position]
                    and (
                        position not in conditioned
                        or _holds(grammar, rule, (start, end), count)
                    )
                ]
                for rule in present:
                    if rule.left in support[start] and _holds(
                        grammar, rule, (start, start, end), count
                    ):
                        edges.append((rule.right, rule.result))
                    if rule.right in support[end] and _holds(
                        grammar, rule, (start, end, end), count
                    ):
                        edges.append((rule.left, rule.result))
                key = tuple(sorted(set(edges)))
                if key not in closures:
                    closures[key] = _boolean_closure(size, key, device)
                    count.products += size**3 * max(size - 1, 1).bit_length()
                closed[start] = (cells[start] @ closures[key] > 0).to(torch.float64)
                count.products += size * size
            cells = closed
        chart[width] = cells
    return {width: cells > 0 for width, cells in chart.items()}, count.report()

Cited sources

Stuart M. Shieber, Yves Schabes, and Fernando C. N. Pereira. Principles and Implementation of Deductive Parsing. The Journal of Logic Programming, 24(1–2):3–36, 1995. URL: https://www.sciencedirect.com/science/article/pii/074310669500035I, doi:10.1016/0743-1066(95)00035-I.

Joshua Goodman. Semiring Parsing. Computational Linguistics, 25(4):573–606, 1999. URL: https://aclanthology.org/J99-4004/.

Joachim Lambek. The Mathematics of Sentence Structure. The American Mathematical Monthly, 65(3):154–170, 1958. URL: https://www.tandfonline.com/doi/abs/10.1080/00029890.1958.11989160, doi:10.1080/00029890.1958.11989160.