Skip to content

Inside Algorithm

The inside algorithm computes, by dynamic programming over CKY spans, the semiring sum over all derivations of a span of the product of their weights (Goodman, 1999). This module computes these inside weights in log space. The weight of the whole sentence is its log probability only when the grammar is a normalized PCFG.

A rule of probability zero has the log weight \(-\infty\) exactly, so a sentence without a derivation scores \(-\infty\). The split points of each premise pair are summed before the rules apply, as in the span plans, so no product over categories and split points together is kept. The derivative of \(\log P\) in a probability \(p\) is \((\partial P / \partial p) / P\), and the backward pass computes \(\partial P / \partial p\) by the outside pass in the log semiring, as a sum of products of outside and inside weights with no factor \(p\). It is thus exact where \(p\) is zero, where differentiating \(\log p\) would multiply zero by an infinite slope, and it keeps only the chart. A sentence without a derivation has derivative zero.

inside

CKY inside algorithm for probabilistic context-free grammars.

Implements the inside algorithm as a differentiable PyTorch module, enabling end-to-end gradient-based learning of PCFG parameters.

A PCFG is specified by two stochastic morphisms:

  • binary : N -> N * N: binary production probabilities. For each nonterminal A, binary[A, B, C] is the probability of the rule A -> B C.
  • lexical : N -> T: terminal production probabilities. For each nonterminal A, lexical[A, t] is the probability of the rule A -> t.

The inside algorithm computes, for each nonterminal A and span (i, j) of the input sentence:

beta(A, i, j) = P(w_i ... w_{j-1} | A)

The sentence log-probability is log beta(start, 0, L) where start is the start symbol index (default 0).

All computation is done in log-space for numerical stability, using logsumexp for marginalization. This preserves gradient flow for learning rule probabilities end-to-end.

Unary rules

An optional unary morphism adds rules A -> B. A chain of them derives a category over a span from another over the same span, so each chart cell is closed once under the closure matrix U* = (I - U)^{-1} of Stolcke (1995), section 4.5.2, which sums the probability of every chain exactly once.

What it computes

The algorithm computes a function from nonempty terminal strings to their inside weights under the start symbol: the sum, over the parse trees of the string, of the product of the weights of the rules in the tree. When the rule weights of each nonterminal form a probability distribution over its productions, this is the string's probability.

Examples:

>>> from quivers.core.objects import FinSet, ProductSet
>>> from quivers.stochastic.morphisms import StochasticMorphism
>>> N = FinSet(name="N", cardinality=5)
>>> T = FinSet(name="T", cardinality=10)
>>> binary = StochasticMorphism(N, ProductSet(N, N))
>>> lexical = StochasticMorphism(N, T)
>>> cky = InsideAlgorithm(binary, lexical, start=0)
>>> tokens = torch.randint(0, 10, (4, 6))  # batch=4, length=6
>>> log_probs = cky(tokens)  # (4,)

InsideAlgorithm

InsideAlgorithm(binary: Morphism, lexical: Morphism, start: int = 0, unary: Morphism | None = None)

Bases: Module

CKY inside algorithm for differentiable PCFG parsing.

Computes sentence log-probabilities under a PCFG defined by binary and lexical production rules, both expressed as stochastic morphisms.

PARAMETER DESCRIPTION
binary

Binary production rules. Must be a morphism N -> N * N where N is a finite set of nonterminals. The tensor has shape (|N|, |N|, |N|) with binary[A, B, C] = P(A -> B C).

TYPE: Morphism

lexical

Lexical (terminal) production rules. Must be a morphism N -> T where T is a finite set of terminals. The tensor has shape (|N|, |T|) with lexical[A, t] = P(A -> t).

TYPE: Morphism

start

Index of the start symbol in N (default 0).

TYPE: int DEFAULT: 0

unary

Optional unary production rules, a morphism N -> N read in the derivation direction: unary[B, A] is the probability of the rule A -> B, which derives A over a span from B over the same span. Each chart cell is closed under these rules once, by the matrix U* = I + U + U² + ... = (I - U)⁻¹, so a chain of unary rules is counted once Stolcke (1995), section 4.5.2.

TYPE: Morphism or None DEFAULT: None

RAISES DESCRIPTION
TypeError

If the morphisms have incompatible types.

Notes

The closure exists only when the spectral radius of U is below one; a row-stochastic U (every category rewrites by some unary rule with probability one) has spectral radius one, and parsing with it raises DivergentClosureError.

Source code in src/quivers/stochastic/inside.py
def __init__(
    self,
    binary: Morphism,
    lexical: Morphism,
    start: int = 0,
    unary: Morphism | None = None,
) -> None:
    super().__init__()
    if not isinstance(binary.codomain, ProductSet):
        raise TypeError(
            f"binary morphism codomain must be a ProductSet, got {binary.codomain!r}"
        )
    if binary.domain != lexical.domain:
        raise TypeError(
            f"binary and lexical must share the same domain (nonterminals), got {binary.domain!r} and {lexical.domain!r}"
        )
    if unary is not None:
        if unary.domain != binary.domain or unary.codomain != binary.domain:
            raise TypeError(
                f"unary morphism must have shape N -> N matching binary "
                f"domain {binary.domain!r}; got {unary.domain!r} -> {unary.codomain!r}"
            )
    self._binary = binary
    self._lexical = lexical
    self._unary = unary
    self._start = start
    self._n_nonterm = binary.domain.size
    self._n_term = lexical.codomain.size
    self._binary_mod = binary.module()
    self._lexical_mod = lexical.module()
    if unary is not None:
        self._unary_mod = unary.module()
    else:
        self._unary_mod = None

n_nonterminals property

n_nonterminals: int

Number of nonterminal symbols.

RETURNS DESCRIPTION
int

The count.

n_terminals property

n_terminals: int

Number of terminal symbols.

RETURNS DESCRIPTION
int

The count.

start property

start: int

Index of the start symbol.

RETURNS DESCRIPTION
int

The index.

forward

forward(tokens: Tensor) -> Tensor

Compute sentence log-probabilities via the inside algorithm.

PARAMETER DESCRIPTION
tokens

Integer tensor of terminal indices. Shape (batch, seq_len) or (seq_len,) for a single sentence.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Log-probability of each sentence under the grammar. Shape (batch,) or scalar for a single sentence.

RAISES DESCRIPTION
ValueError

If the sentences are empty.

DivergentClosureError

If the unary rules' closure diverges.

Source code in src/quivers/stochastic/inside.py
def forward(self, tokens: torch.Tensor) -> torch.Tensor:
    """Compute sentence log-probabilities via the inside algorithm.

    Parameters
    ----------
    tokens : torch.Tensor
        Integer tensor of terminal indices. Shape
        ``(batch, seq_len)`` or ``(seq_len,)`` for a single
        sentence.

    Returns
    -------
    torch.Tensor
        Log-probability of each sentence under the grammar.
        Shape ``(batch,)`` or scalar for a single sentence.

    Raises
    ------
    ValueError
        If the sentences are empty.
    DivergentClosureError
        If the unary rules' closure diverges.
    """
    squeeze = False
    if tokens.dim() == 1:
        tokens = tokens.unsqueeze(0)
        squeeze = True
    if tokens.shape[1] == 0:
        raise ValueError("cannot parse empty sentences")
    binary, lexical, unary = self._tensors()
    empty = binary.new_zeros((0,))
    result = _InsideOutside.apply(
        binary, lexical, unary if unary is not None else empty, tokens, self._start
    )
    if squeeze:
        return result.squeeze(0)
    return result

inside_chart

inside_chart(tokens: Tensor) -> Tensor

Compute the full inside chart (for analysis/debugging).

PARAMETER DESCRIPTION
tokens

Integer tensor of terminal indices. Shape (batch, seq_len) or (seq_len,).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The full inside chart in log-space. Shape (batch, N, seq_len, seq_len+1) where entry [b, A, i, j] is log P(w_i..w_{j-1} | A).

RAISES DESCRIPTION
ValueError

If the sentences are empty.

Source code in src/quivers/stochastic/inside.py
def inside_chart(self, tokens: torch.Tensor) -> torch.Tensor:
    """Compute the full inside chart (for analysis/debugging).

    Parameters
    ----------
    tokens : torch.Tensor
        Integer tensor of terminal indices. Shape
        ``(batch, seq_len)`` or ``(seq_len,)``.

    Returns
    -------
    torch.Tensor
        The full inside chart in log-space. Shape
        ``(batch, N, seq_len, seq_len+1)`` where entry
        ``[b, A, i, j]`` is ``log P(w_i..w_{j-1} | A)``.

    Raises
    ------
    ValueError
        If the sentences are empty.
    """
    squeeze = False
    if tokens.dim() == 1:
        tokens = tokens.unsqueeze(0)
        squeeze = True
    if tokens.shape[1] == 0:
        raise ValueError("cannot parse empty sentences")
    cells = self._fill_chart(tokens)
    batch, length = tokens.shape
    chart = torch.full(
        (batch, self._n_nonterm, length, length + 1),
        -torch.inf,
        dtype=cells[1].dtype,
        device=cells[1].device,
    )
    for width in range(1, length + 1):
        for start in range(length - width + 1):
            chart[:, :, start, start + width] = cells[width][:, start]
    if squeeze:
        return chart.squeeze(0)
    return chart

__repr__

__repr__() -> str

The sizes of the grammar.

RETURNS DESCRIPTION
str

The representation.

Source code in src/quivers/stochastic/inside.py
def __repr__(self) -> str:
    """The sizes of the grammar.

    Returns
    -------
    str
        The representation.
    """
    return f"InsideAlgorithm(N={self._n_nonterm}, T={self._n_term}, start={self._start})"

Cited sources

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