Skip to content

Spanning trees

A directed spanning tree of nodes \(0, \dots, n-1\) rooted at \(r\) (an arborescence) gives every node except \(r\) one parent and has no cycle. weights[..., x, y] is the weight \(W[x, y]\) of the edge from parent \(x\) to child \(y\); self edges, edges into the root and edges a mask removes are absent. The partition function is

\[ Z(W) = \sum_{T} \prod_{(x \to y) \in T} W[x, y], \]

and tree_partition computes it in a zero-sum-free Semifield: in the log semifield the log partition, in the linear one the partition, in the max-plus one the weight of the best tree, in the Boolean one whether a tree exists. directed_tree wraps the weights, root, algebra and mask as a DirectedTrees.

Elimination without subtraction

For a node \(k \ne r\) let \(\mathrm{in}(k) = \bigoplus_{x} W[x, k]\), its total incoming weight. On the nodes other than \(k\) define

\[ W'[x, y] = W[x, y] \oplus W[x, k] \otimes W[k, y] \oslash \mathrm{in}(k) \qquad (x \ne y). \]

Theorem. In every commutative semifield, if \(\mathrm{in}(k)\) is not zero, then \(Z(W) = \mathrm{in}(k) \otimes Z(W')\).

Proof. Over the real numbers, let \(L\) be the Laplacian with \(L[y, y] = \mathrm{in}(y)\) and \(L[x, y] = -W[x, y]\) for \(x \ne y\), and \(\hat L\) the matrix without the root's row and column. The matrix-tree theorem for directed graphs (Tutte 1984) gives \(Z(W) = \det \hat L\). Pivoting on \(L[k, k] = \mathrm{in}(k)\) gives \(\det \hat L = \mathrm{in}(k) \det S\), where the Schur complement has entries \(S[x, y] = L[x, y] - L[x, k] L[k, y] / \mathrm{in}(k)\). Off the diagonal this is \(-W'[x, y]\). On the diagonal it is \(\mathrm{in}(y) - W[y, k] W[k, y] / \mathrm{in}(k)\), and the incoming weight of \(y\) under \(W'\) is

\[ \sum_{x \ne y, k} \Big( W[x, y] + \frac{W[x, k] W[k, y]}{\mathrm{in}(k)} \Big) = \mathrm{in}(y) - W[k, y] + W[k, y] \frac{\mathrm{in}(k) - W[y, k]}{\mathrm{in}(k)} = \mathrm{in}(y) - \frac{W[y, k] W[k, y]}{\mathrm{in}(k)}. \]

So \(S\) is the Laplacian of \(W'\) without the root, and \(Z(W) = \mathrm{in}(k) Z(W')\) for positive real weights. Now \(Z\) is homogeneous of degree \(n - 1\) in the weights of a tree on \(n\) nodes, so \(\mathrm{in}(k)^{n-2} Z(W') = Z(W'')\) with \(W''[x, y] = W[x, y]\,\mathrm{in}(k) + W[x, k] W[k, y]\). The identity \(\mathrm{in}(k)^{n-2} Z(W) = \mathrm{in}(k)\, Z(W'')\) is then an equality of polynomials with nonnegative integer coefficients that holds on the positive orthant, an open set, so the two polynomials have the same coefficients. It therefore holds in every commutative semiring. In a semifield with \(\mathrm{in}(k)\) not zero, multiplying by the inverse of \(\mathrm{in}(k)^{n-2}\) and using homogeneity again gives \(Z(W) = \mathrm{in}(k) \otimes Z(W')\). QED

Eliminating every node but the root leaves the empty tree, whose weight is the unit, so \(Z(W)\) is the product of the pivots. Each step costs \(O(n^2)\) operations, the whole \(O(n^3)\), and no step subtracts. Subtraction-free circuits of this size exist and circuits with sums and products alone need exponential size (Fomin, Grigoriev and Koshevoy 2016); whether a subtraction-free circuit below \(n^3\) exists is open. With subtraction, a determinant costs \(O(n^\omega)\), but it cancels: for edge log weights \(-60\) and \(-61\) from the root and a unit cycle between the two other nodes, the log partition is \(-59.6867\), which elimination computes exactly, while the log determinant of the Laplacian in float64 is \(-\infty\), since \(1 + e^{-60}\) rounds to \(1\).

Zero pivots. The algebra must be zero-sum-free, so a pivot is zero exactly when every incoming weight of its node is. A node with a nonzero pivot is eliminated first. If the nodes left all have zero pivots and two or more remain, no tree exists, every monomial of \(Z\) holds an incoming weight of each of them, and every first derivative vanishes: the result is the zero with derivative zero. If one remains, the partition is the product of the pivots, the last zero; where the algebra's zero is a finite number its derivative is that of the product, which keeps the derivative at a weight that is zero but differentiable, and where the zero lies at infinity (log space) the representation is not differentiable there and its derivative is zero.

Checked directed tree query

QVR's directed_tree_log_partition(scores, root, mask) returns a LogWeight for one graph. The scores have type Real[Fin n, Fin n], the Boolean mask has the same axes, and the Int root is a zero-based index in the nonempty node inventory. The first axis gives the parent and the second gives the child. Every other node has exactly one incoming edge. The root may have several children, and edges may cross in the given node order. Self-edges, edges into the root, false mask entries, and negative-infinity scores exclude edges.

The query uses the subtraction-free elimination above. The total mass of the singleton graph is one. If no tree exists, its log mass is negative infinity with a zero tangent. At positive mass the derivative with respect to each admitted finite log score is the edge marginal. The query refuses nonfinite admitted scores other than negative infinity and finite scores outside a conservative working range. When elimination returns negative infinity, the same elimination over Booleans checks whether the graph has a tree before returning zero mass. The exact statement concerns support, with no bound on rounding error for finite log masses.

The dense schedule performs \(O(n^3)\) operations forward and in the first reverse pass. It holds \(O(n^2)\) forward tensor lanes apart from the reverse tape, which can save \(O(n^3)\) lanes across the elimination steps. The extra Boolean support check also takes \(O(n^3)\) operations and has no reverse tape. The checked query is native to Quivers.

Edge marginals

tree_marginals is the derivative of the partition with respect to each weight: in the log semifield, \(\partial \log Z / \partial \log W[x, y]\), the probability of the edge under the normalized tree weights; in the max-plus semifield, the indicator of the best tree. It is the derivative of the elimination, so it costs a constant times the partition (Baur and Strassen 1983), and it can be differentiated again.

Erratum. Andrews, Eisner and Dredze (2012, section 6) define the Laplacian by their equation 12, \(L[x, y] = -\delta(y \mid x)\) for \(x \ne y\) and \(L[y, y] = \sum_{x'} \delta(y \mid x')\), and give the marginals in equation 14 as \(\delta(y \mid x)(\hat L^{-1}_{xx} - \hat L^{-1}_{xy})\) for \(x \ne y\). The derivative of \(\log \det \hat L\) under equation 12 is \(\delta(y \mid x)(\hat L^{-1}_{yy} - \hat L^{-1}_{yx})\), since \(\partial \log \det \hat L / \partial \hat L_{ij} = \hat L^{-1}_{ji}\) and \(\delta(y \mid x)\) enters \(\hat L_{xy}\) with sign \(-1\) and \(\hat L_{yy}\) with sign \(+1\). This module implements the derivative of equation 12; on a four-node graph the printed form of equation 14 differs from enumeration of every tree by more than \(0.1\), and the derivative agrees with it to rounding.

References

  • Tutte, W. T. (1984). Graph Theory. Addison-Wesley.
  • Koo, T., Globerson, A., Carreras, X., and Collins, M. (2007). Structured prediction models via the matrix-tree theorem. EMNLP-CoNLL. D07-1015
  • Andrews, N., Eisner, J., and Dredze, M. (2012). Name phylogeny: a generative model of string variation. EMNLP-CoNLL, 344-355. D12-1032
  • Fomin, S., Grigoriev, D., and Koshevoy, G. (2016). Subtraction-free complexity, cluster transformations, and spanning trees. Foundations of Computational Mathematics. doi:10.1007/s10208-014-9231-y
  • Baur, W., and Strassen, V. (1983). The complexity of partial derivatives. Theoretical Computer Science 22, 317-330. doi:10.1016/0304-3975(83)90110-X

spanning

Directed spanning trees: partition functions and edge marginals.

A directed spanning tree (an arborescence) of nodes 0, ..., n-1 rooted at r gives every node except r exactly one parent and has no cycle. weights[..., x, y] is the weight of the edge from parent x to child y. The partition function sums, over every such tree, the product of its edge weights; self edges, edges into the root, and edges a mask removes are absent.

The partition is computed by eliminating the nodes other than the root one at a time, with sums, products and quotients of the algebra and no subtraction: for a node k with total incoming weight in(k) = ⊕_x W[x, k],

Z(W) = in(k) ⊗ Z(W'),   W'[x, y] = W[x, y] ⊕ W[x, k] ⊗ W[k, y] ⊘ in(k),

on the nodes other than k. The identity holds in every commutative semifield; the proof is in the API page of this module. Each step costs O(n^2) operations, so the partition costs O(n^3). Determinants need subtraction, and in floating point the determinant of a badly scaled Laplacian can cancel to zero where the partition is not: for edge log weights -60 and -61 from the root and a unit cycle between the other two nodes the partition is -59.6867 in log space, which elimination computes exactly, while a log determinant returns -inf.

Edge marginals are the derivative of the partition with respect to the weights: in the log semifield the probability of each edge under the normalized tree weights, in the max-plus semifield the indicator of the best tree by the algebra's tie rule.

References

Tutte, W. T. (1984). Graph Theory. Addison-Wesley.

Koo, T., Globerson, A., Carreras, X., and Collins, M. (2007). Structured prediction models via the matrix-tree theorem. EMNLP-CoNLL, 141-150. https://aclanthology.org/D07-1015/

Andrews, N., Eisner, J., and Dredze, M. (2012). Name phylogeny: a generative model of string variation. EMNLP-CoNLL, 344-355. https://aclanthology.org/D12-1032/

DirectedTrees didactic-model

DirectedTrees(*, weights: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), root: int, algebra: Semifield = field(opaque=True, extras=OPAQUE_BY_IDENTITY), mask: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

The directed spanning trees of a weighted graph with a given root.

PARAMETER DESCRIPTION
weights

Shape (*batch, n, n); weights[..., x, y] weights the edge from parent x to child y.

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

root

The root.

TYPE: int

algebra

A zero-sum-free semifield with scalar elements.

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

mask

A boolean mask broadcastable to the weights.

TYPE: Tensor or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

partition

partition() -> Tensor

The partition function; in the log semifield, the log partition.

RETURNS DESCRIPTION
Tensor

Shape batch.

Source code in src/quivers/core/spanning.py
def partition(self) -> torch.Tensor:
    """The partition function; in the log semifield, the log partition.

    Returns
    -------
    torch.Tensor
        Shape ``batch``.
    """
    return tree_partition(
        self.weights, self.root, algebra=self.algebra, mask=self.mask
    )

edge_marginals

edge_marginals() -> Tensor

The derivative of the partition with respect to each edge weight.

RETURNS DESCRIPTION
Tensor

Shape (*batch, n, n).

Source code in src/quivers/core/spanning.py
def edge_marginals(self) -> torch.Tensor:
    """The derivative of the partition with respect to each edge weight.

    Returns
    -------
    torch.Tensor
        Shape ``(*batch, n, n)``.
    """
    return tree_marginals(
        self.weights, self.root, algebra=self.algebra, mask=self.mask
    )

tree_partition

tree_partition(weights: Tensor, root: int, *, algebra: Semifield = LOG_PROB, mask: Tensor | None = None) -> Tensor

The partition function over directed spanning trees with a given root.

Nodes are eliminated in an order chosen per graph: at each step, a remaining node whose incoming weight is not zero. When every remaining node has zero incoming weight and two or more remain, there is no tree, and every first derivative of the partition vanishes, so the result is the zero with derivative zero. When one remains, the partition is the product of the pivots, the last of them zero; where the algebra's zero is a finite number its derivative is the derivative of that product, and where the zero lies at infinity, as -inf in log space, the partition is not differentiable there and its derivative is zero. A zero is decided by the algebra, so a weight that is zero but differentiable keeps its derivative.

PARAMETER DESCRIPTION
weights

Shape (*batch, n, n); weights[..., x, y] weights the edge from parent x to child y.

TYPE: Tensor

root

The root, which has no parent.

TYPE: int

algebra

A zero-sum-free semifield with scalar elements; the log semifield by default.

TYPE: Semifield DEFAULT: LOG_PROB

mask

A boolean mask broadcastable to the weights; False removes an edge.

TYPE: Tensor or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Shape batch: the partition, the algebra's unit for one node, and its zero when there is no tree.

RAISES DESCRIPTION
TypeError

If the algebra is not a zero-sum-free semifield with scalar elements.

ValueError

If the weights are not square or the root is not a node.

Source code in src/quivers/core/spanning.py
def tree_partition(
    weights: torch.Tensor,
    root: int,
    *,
    algebra: Semifield = LOG_PROB,
    mask: torch.Tensor | None = None,
) -> torch.Tensor:
    """The partition function over directed spanning trees with a given root.

    Nodes are eliminated in an order chosen per graph: at each step, a
    remaining node whose incoming weight is not zero. When every remaining
    node has zero incoming weight and two or more remain, there is no tree,
    and every first derivative of the partition vanishes, so the result is
    the zero with derivative zero. When one remains, the partition is the
    product of the pivots, the last of them zero; where the algebra's zero
    is a finite number its derivative is the derivative of that product,
    and where the zero lies at infinity, as ``-inf`` in log space, the
    partition is not differentiable there and its derivative is zero. A
    zero is decided by the algebra, so a weight that is zero but
    differentiable keeps its derivative.

    Parameters
    ----------
    weights : torch.Tensor
        Shape ``(*batch, n, n)``; ``weights[..., x, y]`` weights the edge
        from parent ``x`` to child ``y``.
    root : int
        The root, which has no parent.
    algebra : Semifield
        A zero-sum-free semifield with scalar elements; the log semifield
        by default.
    mask : torch.Tensor or None
        A boolean mask broadcastable to the weights; False removes an edge.

    Returns
    -------
    torch.Tensor
        Shape ``batch``: the partition, the algebra's unit for one node,
        and its zero when there is no tree.

    Raises
    ------
    TypeError
        If the algebra is not a zero-sum-free semifield with scalar
        elements.
    ValueError
        If the weights are not square or the root is not a node.
    """
    nodes = _require(algebra, weights, root)
    batch = tuple(weights.shape[:-2])
    allowed = _allowed(nodes, root, mask, weights)
    zero = algebra.zero_like(tuple(weights.shape), weights)
    current = torch.where(allowed, weights, zero)
    total = algebra.unit_like(batch, weights)
    if nodes == 1 and weights.requires_grad:
        # The only edge is a self edge. Mask it before arithmetic so that
        # the empty tree has a differentiable zero even at nonfinite scores.
        score = weights[..., 0, 0]
        masked = torch.where(
            torch.zeros_like(score, dtype=torch.bool), score, torch.zeros_like(score)
        )
        return total + masked.square()
    remaining = torch.ones((*batch, nodes), dtype=torch.bool, device=weights.device)
    remaining[..., root] = False
    dead = torch.zeros(batch, dtype=torch.bool, device=weights.device)
    off_diagonal = ~torch.eye(nodes, dtype=torch.bool, device=weights.device)
    for _ in range(nodes - 1):
        pivots = algebra.join(current, -2)
        live = remaining & ~algebra.is_zero(pivots)
        has_live = live.any(dim=-1)
        choice = torch.where(
            has_live,
            live.to(torch.int8).argmax(dim=-1),
            remaining.to(torch.int8).argmax(dim=-1),
        )
        last = remaining.sum(dim=-1) == 1
        dead = dead | (~has_live & ~last)
        index = choice.unsqueeze(-1)
        pivot = torch.take_along_dim(pivots, index, dim=-1).squeeze(-1)
        total = algebra.tensor_op(total, pivot)
        safe = torch.where(
            algebra.is_zero(pivot), algebra.unit_like(batch, weights), pivot
        )
        column = torch.take_along_dim(current, index.unsqueeze(-2), dim=-1).squeeze(-1)
        row = torch.take_along_dim(current, index.unsqueeze(-1), dim=-2).squeeze(-2)
        through = algebra.divide(
            algebra.tensor_op(column.unsqueeze(-1), row.unsqueeze(-2)),
            safe.unsqueeze(-1).unsqueeze(-1),
        )
        removed = torch.nn.functional.one_hot(choice, nodes).to(torch.bool)
        remaining = remaining & ~removed
        # A contracted path through the eliminated node is an edge of the
        # smaller graph even where the mask removed the direct edge; only
        # self edges and the eliminated node's own edges are dropped.
        keep = off_diagonal & ~removed.unsqueeze(-1) & ~removed.unsqueeze(-2)
        current = torch.where(
            keep, algebra.join(torch.stack((current, through)), 0), zero
        )
    # Where the algebra's zero is a finite number (the linear semifields),
    # a partition of zero with a live weight keeps the derivative of the
    # product of the pivots. Where the zero lies at infinity (log space),
    # the representation is not differentiable there, and its derivative
    # is zero.
    zero_result = algebra.zero_like(batch, weights)
    at_infinity = algebra.is_zero(total) & ~torch.isfinite(zero_result)
    return torch.where(dead | at_infinity, zero_result, total)

tree_marginals

tree_marginals(weights: Tensor, root: int, *, algebra: Semifield = LOG_PROB, mask: Tensor | None = None) -> Tensor

The derivative of the partition with respect to each edge weight.

This is the derivative of the partition itself, so it is right wherever the partition is: in the log semifield it is the marginal probability of each edge; in the max-plus semifield, the indicator of the best tree. The derivative is part of the autograd graph, so it can be differentiated again.

PARAMETER DESCRIPTION
weights

Shape (*batch, n, n).

TYPE: Tensor

root

The root.

TYPE: int

algebra

A zero-sum-free semifield with scalar elements.

TYPE: Semifield DEFAULT: LOG_PROB

mask

A boolean mask broadcastable to the weights.

TYPE: Tensor or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Shape (*batch, n, n); zero for absent edges and for graphs with no tree.

RAISES DESCRIPTION
TypeError

If the algebra is not a zero-sum-free semifield with scalar elements.

ValueError

If the weights are not square or the root is not a node.

Source code in src/quivers/core/spanning.py
def tree_marginals(
    weights: torch.Tensor,
    root: int,
    *,
    algebra: Semifield = LOG_PROB,
    mask: torch.Tensor | None = None,
) -> torch.Tensor:
    """The derivative of the partition with respect to each edge weight.

    This is the derivative of the partition itself, so it is right
    wherever the partition is: in the log semifield it is the marginal
    probability of each edge; in the max-plus semifield, the indicator of
    the best tree. The derivative is part of the autograd graph, so it can
    be differentiated again.

    Parameters
    ----------
    weights : torch.Tensor
        Shape ``(*batch, n, n)``.
    root : int
        The root.
    algebra : Semifield
        A zero-sum-free semifield with scalar elements.
    mask : torch.Tensor or None
        A boolean mask broadcastable to the weights.

    Returns
    -------
    torch.Tensor
        Shape ``(*batch, n, n)``; zero for absent edges and for graphs
        with no tree.

    Raises
    ------
    TypeError
        If the algebra is not a zero-sum-free semifield with scalar
        elements.
    ValueError
        If the weights are not square or the root is not a node.
    """
    source = weights if weights.requires_grad else weights.detach().requires_grad_()
    partition = tree_partition(source, root, algebra=algebra, mask=mask)
    (gradient,) = torch.autograd.grad(
        partition.sum(), source, create_graph=weights.requires_grad
    )
    return gradient

directed_tree

directed_tree(weights: Tensor, *, root: int, algebra: Semifield = LOG_PROB, mask: Tensor | None = None) -> DirectedTrees

The directed spanning trees of a graph with a given root.

PARAMETER DESCRIPTION
weights

Shape (*batch, n, n); in the default log semifield, edge log weights.

TYPE: Tensor

root

The root.

TYPE: int

algebra

A zero-sum-free semifield with scalar elements.

TYPE: Semifield DEFAULT: LOG_PROB

mask

A boolean mask broadcastable to the weights.

TYPE: Tensor or None DEFAULT: None

RETURNS DESCRIPTION
DirectedTrees

The distribution, with DirectedTrees.partition and DirectedTrees.edge_marginals.

Source code in src/quivers/core/spanning.py
def directed_tree(
    weights: torch.Tensor,
    *,
    root: int,
    algebra: Semifield = LOG_PROB,
    mask: torch.Tensor | None = None,
) -> DirectedTrees:
    """The directed spanning trees of a graph with a given root.

    Parameters
    ----------
    weights : torch.Tensor
        Shape ``(*batch, n, n)``; in the default log semifield, edge log
        weights.
    root : int
        The root.
    algebra : Semifield
        A zero-sum-free semifield with scalar elements.
    mask : torch.Tensor or None
        A boolean mask broadcastable to the weights.

    Returns
    -------
    DirectedTrees
        The distribution, with `DirectedTrees.partition` and
        `DirectedTrees.edge_marginals`.
    """
    return DirectedTrees(weights=weights, root=root, algebra=algebra, mask=mask)