Skip to content

Contractions

A contraction \(x_1, \dots, x_k \to y\) names each axis of each input by a letter. With \(\mathcal L\) the letters, \(Y\) the output letters and \(\mathcal L_c = \mathcal L \setminus Y\) the summed ones, its value is

\[ \Phi(T_1, \dots, T_k)[y] = \bigoplus_{c} \bigotimes_{i=1}^{k} T_i\bigl[(y, c)|_{x_i}\bigr]. \]

plan_contraction fixes how it is evaluated from the letters, their extents and the algebra's law claims, and records the result as a ContractionPlan; run_contraction evaluates a plan and counts its work. EinsumWiring, binary composition (CompositionRule.compose) and day_convolution all run through them.

algebra algorithm cost status
establishes every law of ELIMINATION_LAWS variable elimination \(O((k + s)\,W)\) time, \(O((s + 1)\,W)\) space (CONTRACTION_WORK) conditional on the exponential time hypothesis
any other the written order \(O(k\,U)\) time, \(O(U)\) space (WRITTEN_ORDER_WORK) unresolved

Here \(s = |\mathcal L_c|\), \(W\) is the number of elements of the largest bag of the chosen order (or of the output, when that is larger), and \(U\) is the product of every extent.

Elimination

For a summed letter \(v\) let \(F_v\) be the factors that contain it and \(B_v\) the letters of \(F_v\), its bag. One step replaces \(F_v\) by the single factor

\[ g[B_v \setminus \{v\}] = \bigoplus_{v} \bigotimes_{f \in F_v} f, \]

summing at the same time every other summed letter whose factors all lie in \(F_v\).

Theorem. In a commutative semiring, a step leaves the value of the contraction unchanged.

Proof. Write the product of all factors as \(P \otimes Q\), with \(P\) the product of \(F_v\) and \(Q\) that of the others. \(Q\) does not depend on \(v\), so by commutativity and associativity of \(\oplus\) the sum over \(\mathcal L_c\) is a sum over \(\mathcal L_c \setminus \{v\}\) of a sum over \(v\), and by distributivity \(\bigoplus_v P \otimes Q = (\bigoplus_v P) \otimes Q\). Reordering the product needs \(\otimes\) commutative and associative. An index range of size zero makes a sum empty, which is the zero, and the zero annihilates the product it enters; a product of no factors is the unit. These are the laws of ELIMINATION_LAWS. QED.

Each law is read from the algebra's claims through Lawful.establishes, never from its name, so an inline rule whose laws are only declared is evaluated in the written order. The order is chosen by elimination_order, cheapest bag first by its elements, ties in order of first mention. Finding an order of least width is NP-hard (Arnborg, Corneil and Proskurowski 1987), so the plan records the order, its bags and their widths and claims nothing about them. The same function orders the variables of a rule body in eliminate, with the number of variables of a bag as its cost.

A step multiplies \(|F_v| - 1\) times over \(B_v\) and sums \(|B_v|\) terms into \(|B_v| / n_v\) results. Every factor is joined once, and \(k + s\) factors exist at most, so the products are at most \((k + s)\,W\) and the sums at most \(s\,W\); the factors held between steps are at most one per step. This gives the bounds above (Dechter 1999; Abo Khamis, Ngo and Rudra 2016 for semirings). For a line of \(k\) matrices of order \(n\), \(W = n^3\), where the written order forms a tensor of \(n^{k+1}\) elements.

At a tie of a selective sum, each sum gives the whole derivative to its first best term, so the contraction gives it to the first best index in the order of elimination.

The written order

An algebra that does not establish the laws, such as ProductFuzzyAlgebra, is evaluated as the formula is written: every input is aligned to all letters, the inputs are multiplied left to right, and the summed letters are summed at once. No law moves a sum inside a product, so whether fewer operations suffice is open for such an algebra. A rule whose elements have axes of their own, such as a MatrixSemiring, keeps them last and keeps the order of its factors.

Work

EinsumWiring.apply_with_work returns a WorkReport of the execution: products, binary sums (a sum of \(m\) terms is \(m - 1\) of them), elements formed, and the largest number of formed elements held at once, each in elements of the algebra; divisions, pivots, comparisons and hashing are measured as zero. The evidence harness checks these counts against a dispatch counter and the claims on growing families.

elimination

Contractions of tensor networks by variable elimination.

A contraction x_1, ..., x_k -> y names each axis of each input by a letter. Its value at an index of the output letters is the sum, over every index of the letters that are not in the output, of the product of the inputs' entries at that index. Evaluated as written, the product of all inputs is formed over every letter before anything is summed, so the largest tensor has the product of all extents as its size.

In a commutative semiring the sum distributes over the product, and both may be regrouped and reordered. A summed letter can thus be removed by multiplying only the factors that contain it and summing it away, which replaces them by one factor over the other letters of their bag (variable elimination; Dechter 1999, and InsideOut of Abo Khamis, Ngo and Rudra 2016 for semirings). The work is bounded by the elements of the largest bag of the chosen order instead of the product of all extents. Finding an order of least width is NP-hard (Arnborg, Corneil and Proskurowski 1987), so elimination_order chooses one greedily, and the plan records the order and its widths without claiming them least.

The laws are read from the algebra's claims, never from its name: an algebra that establishes every law of ELIMINATION_LAWS is eliminated, and any other is evaluated in the written order, with its products taken left to right in the order of the inputs.

References

Dechter, R. (1999). Bucket elimination: a unifying framework for reasoning. Artificial Intelligence 113(1-2), 41-85. doi:10.1016/S0004-3702(99)00059-4

Abo Khamis, M., Ngo, H. Q., and Rudra, A. (2016). FAQ: questions asked frequently. PODS, 13-28. doi:10.1145/2902251.2902280

Arnborg, S., Corneil, D. G., and Proskurowski, A. (1987). Complexity of finding embeddings in a k-tree. SIAM Journal on Algebraic and Discrete Methods 8(2), 277-284. doi:10.1137/0608024

ELIMINATION_LAWS module-attribute

The laws elimination reorders by: a commutative semiring on one domain.

Sums are regrouped and reordered, products are regrouped and reordered, a sum is moved inside the product of the factors that do not contain its letter, an absent term is the zero and annihilates its product, a sum over several axes is taken one axis at a time, and a product of no factors is the unit.

ContractionAlgebra

Bases: Protocol

The operations and law claims a contraction uses.

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

The product of two broadcastable tensors, elementwise.

PARAMETER DESCRIPTION
a

The left factor.

TYPE: Tensor

b

The right factor.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a ⊗ b.

Source code in src/quivers/core/elimination.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The product of two broadcastable tensors, elementwise.

    Parameters
    ----------
    a : torch.Tensor
        The left factor.
    b : torch.Tensor
        The right factor.

    Returns
    -------
    torch.Tensor
        ``a ⊗ b``.
    """
    ...

join

join(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The sum over axes.

PARAMETER DESCRIPTION
t

The terms.

TYPE: Tensor

dim

The axes.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The sum with the axes removed.

Source code in src/quivers/core/elimination.py
def join(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The sum over axes.

    Parameters
    ----------
    t : torch.Tensor
        The terms.
    dim : int or tuple of int
        The axes.

    Returns
    -------
    torch.Tensor
        The sum with the axes removed.
    """
    ...

establishes

establishes(*laws: Law) -> bool

Whether every law is claimed and proved or decided.

PARAMETER DESCRIPTION
*laws

The laws.

TYPE: Law DEFAULT: ()

RETURNS DESCRIPTION
bool

True when each is established.

Source code in src/quivers/core/elimination.py
def establishes(self, *laws: Law) -> bool:
    """Whether every law is claimed and proved or decided.

    Parameters
    ----------
    *laws : Law
        The laws.

    Returns
    -------
    bool
        True when each is established.
    """
    ...

ContractionStep didactic-model

ContractionStep(*, letters: tuple[str, ...] = (), factors: tuple[int, ...] = (), bag: tuple[str, ...] = (), elements: int = 0)

Bases: Model

One step of an elimination: factors multiplied, letters summed out.

PARAMETER DESCRIPTION
letters

The letters summed out at this step: the chosen one and every other summed letter whose factors are all joined here.

TYPE: tuple of str DEFAULT: ()

factors

The factors joined: inputs are numbered from zero in order, and the result of step s is factor k + s for k inputs.

TYPE: tuple of int DEFAULT: ()

bag

The letters of the joined factors, in order of first mention.

TYPE: tuple of str DEFAULT: ()

elements

Elements of the product over the bag.

TYPE: int DEFAULT: 0

ContractionPlan didactic-model

ContractionPlan(*, inputs: tuple[str, ...] = (), output: str = '', extents: dict[str, int] = {}, algorithm: Literal['variable elimination', 'written order'] = 'written order', order: tuple[str, ...] = (), steps: tuple[ContractionStep, ...] = (), width: int = 0, largest: int = 0)

Bases: Model

How a contraction is evaluated, fixed before any value is read.

PARAMETER DESCRIPTION
inputs

The letters of each input.

TYPE: tuple of str DEFAULT: ()

output

The letters of the output.

TYPE: str DEFAULT: ''

extents

The extent of each letter, in order of first mention.

TYPE: dict of str to int DEFAULT: {}

algorithm

"variable elimination", or "written order" for an algebra that does not establish ELIMINATION_LAWS.

TYPE: str DEFAULT: 'written order'

order

The summed letters in the order elimination_order chose; empty in the written order.

TYPE: tuple of str DEFAULT: ()

steps

The steps of an elimination; empty in the written order.

TYPE: tuple of ContractionStep DEFAULT: ()

width

Letters of the largest bag less one: the induced width of the order. In the written order, every letter less one.

TYPE: int DEFAULT: 0

largest

Elements of the largest tensor the plan forms: the largest bag or the output, and in the written order the product of every extent.

TYPE: int DEFAULT: 0

summed property

summed: tuple[str, ...]

The letters summed out, in order of first mention.

RETURNS DESCRIPTION
tuple of str

Every letter not in the output.

ContractionCounts didactic-model

ContractionCounts(*, products: int = 0, sums: int = 0, allocated: int = 0, peak: int = 0)

Bases: Model

The work of one contraction, counted in elements of the algebra.

PARAMETER DESCRIPTION
products

Binary products, one per element of each product formed.

TYPE: int DEFAULT: 0

sums

Binary sums: a sum of m terms is m - 1 of them.

TYPE: int DEFAULT: 0

allocated

Elements of the tensors formed.

TYPE: int DEFAULT: 0

peak

Elements of the tensors the plan formed that were held at once, besides the inputs.

TYPE: int DEFAULT: 0

elimination_order

elimination_order(variables: Sequence[str], edges: Sequence[Collection[str]], kept: Collection[str], cost: Callable[[frozenset[str]], float] = len) -> tuple[str, ...]

A greedy order of the variables to sum out: cheapest bag first.

At each step the variable whose bag (the variables of the edges that contain it, itself included) has the least cost is removed, ties in the order of variables; its edges are merged into one without it. Finding an order of least width is NP-hard (Arnborg, Corneil and Proskurowski 1987), so this order is recorded, not claimed least.

PARAMETER DESCRIPTION
variables

Every variable, in the order that breaks ties.

TYPE: Sequence of str

edges

The variables of each factor, and of any constraint that has to see its variables together.

TYPE: Sequence of Collection of str

kept

The variables that are not summed out.

TYPE: Collection of str

cost

A deterministic ordered cost of the bag; its size by default.

TYPE: Callable DEFAULT: len

RETURNS DESCRIPTION
tuple of str

The variables not in kept, in elimination order.

Source code in src/quivers/core/elimination.py
def elimination_order(
    variables: Sequence[str],
    edges: Sequence[Collection[str]],
    kept: Collection[str],
    cost: Callable[[frozenset[str]], float] = len,
) -> tuple[str, ...]:
    """A greedy order of the variables to sum out: cheapest bag first.

    At each step the variable whose bag (the variables of the edges that
    contain it, itself included) has the least cost is removed, ties in
    the order of ``variables``; its edges are merged into one without it.
    Finding an order of least width is NP-hard (Arnborg, Corneil and
    Proskurowski 1987), so this order is recorded, not claimed least.

    Parameters
    ----------
    variables : Sequence of str
        Every variable, in the order that breaks ties.
    edges : Sequence of Collection of str
        The variables of each factor, and of any constraint that has to
        see its variables together.
    kept : Collection of str
        The variables that are not summed out.
    cost : Callable
        A deterministic ordered cost of the bag; its size by default.

    Returns
    -------
    tuple of str
        The variables not in ``kept``, in elimination order.
    """
    # Every factor scope induces a clique. Combining the scopes that
    # contain a variable makes its current neighbors a clique in turn.
    adjacency: dict[str, set[str]] = {name: set() for name in variables}
    for edge in edges:
        scope = frozenset(edge)
        for name in scope:
            neighbors = adjacency.setdefault(name, set())
            neighbors.update(scope)
            neighbors.discard(name)

    position = {name: index for index, name in enumerate(variables)}
    remaining = Counter(name for name in variables if name not in kept)
    scores: dict[str, tuple[float, int, str]] = {}
    agenda: list[tuple[float, int, str]] = []

    def schedule(name: str) -> None:
        """Record a variable's priority for its current bag.

        Parameters
        ----------
        name : str
            A variable still in the elimination order.
        """
        bag = frozenset(adjacency[name] | {name})
        score = (cost(bag), position[name], name)
        scores[name] = score
        heappush(agenda, score)

    for name in remaining:
        schedule(name)

    chosen: list[str] = []
    while remaining:
        score = heappop(agenda)
        best = score[2]
        if scores.get(best) is not score:
            continue
        del scores[best]
        chosen.append(best)
        remaining[best] -= 1
        if remaining[best] == 0:
            del remaining[best]

        neighbors = adjacency[best]
        adjacency[best] = set()
        for name in neighbors:
            other = adjacency[name]
            other.remove(best)
            other.update(neighbors)
            other.discard(name)
            if name in remaining:
                schedule(name)
        if best in remaining:
            schedule(best)

        # Keep only O(number of variables) heap entries across fill rounds.
        if len(agenda) > 2 * len(scores):
            agenda = list(scores.values())
            heapify(agenda)
    return tuple(chosen)

plan_contraction

plan_contraction(algebra: ContractionAlgebra, inputs: Sequence[str], output: str, extents: Mapping[str, int]) -> ContractionPlan

Choose how to evaluate a contraction, from its letters and extents.

PARAMETER DESCRIPTION
algebra

The algebra, whose claims decide between elimination and the written order.

TYPE: ContractionAlgebra

inputs

The letters of each input; no letter repeats within one.

TYPE: Sequence of str

output

The output letters, each in some input and none repeated.

TYPE: str

extents

The extent of every letter.

TYPE: Mapping of str to int

RETURNS DESCRIPTION
ContractionPlan

The plan. Elimination orders its letters by the elements of their bags, ties in order of first mention.

RAISES DESCRIPTION
TypeError

If an input or the output is not a string of letters.

ValueError

If there is no input, a letter repeats within an input or the output, an output letter is in no input, or a letter has no extent or a negative one.

Source code in src/quivers/core/elimination.py
def plan_contraction(
    algebra: ContractionAlgebra,
    inputs: Sequence[str],
    output: str,
    extents: Mapping[str, int],
) -> ContractionPlan:
    """Choose how to evaluate a contraction, from its letters and extents.

    Parameters
    ----------
    algebra : ContractionAlgebra
        The algebra, whose claims decide between elimination and the
        written order.
    inputs : Sequence of str
        The letters of each input; no letter repeats within one.
    output : str
        The output letters, each in some input and none repeated.
    extents : Mapping of str to int
        The extent of every letter.

    Returns
    -------
    ContractionPlan
        The plan. Elimination orders its letters by the elements of their
        bags, ties in order of first mention.

    Raises
    ------
    TypeError
        If an input or the output is not a string of letters.
    ValueError
        If there is no input, a letter repeats within an input or the
        output, an output letter is in no input, or a letter has no
        extent or a negative one.
    """
    if not isinstance(output, str) or any(
        not isinstance(letters, str) for letters in inputs
    ):
        raise TypeError("the inputs and output of a contraction are strings of letters")
    if not inputs:
        raise ValueError("a contraction has at least one input")
    universe = _universe(inputs)
    for name in universe:
        if name not in extents or extents[name] < 0:
            raise ValueError(f"letter {name!r} has no extent of at least zero")
    return _planned(
        algebra.establishes(*ELIMINATION_LAWS),
        tuple(inputs),
        output,
        tuple(int(extents[name]) for name in universe),
    )

run_contraction

run_contraction(plan: ContractionPlan, algebra: ContractionAlgebra, tensors: Sequence[Tensor], element_rank: int = 0) -> tuple[Tensor, ContractionCounts]

Evaluate a contraction by its plan.

In the written order every input is aligned to all letters, the inputs are multiplied left to right, and the summed letters are summed at once. In an elimination each step multiplies the factors it joins over its bag, in the order they were made, and sums its letters away; the factors left are multiplied over the output. At a tie of a selective sum the derivative goes to the first best term of each sum the plan forms, so to the first best index in the order of elimination.

PARAMETER DESCRIPTION
plan

The plan.

TYPE: ContractionPlan

algebra

The algebra the plan was made for.

TYPE: ContractionAlgebra

tensors

The inputs, each with its index axes in the order of its letters and then element_rank element axes.

TYPE: Sequence of torch.Tensor

element_rank

The number of trailing axes of one element of the algebra.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
tuple of torch.Tensor and ContractionCounts

The output, its index axes in the order of the output letters, and the work.

RAISES DESCRIPTION
TypeError

If an input is not a tensor.

ValueError

If the inputs do not fit the plan.

Source code in src/quivers/core/elimination.py
def run_contraction(
    plan: ContractionPlan,
    algebra: ContractionAlgebra,
    tensors: Sequence[torch.Tensor],
    element_rank: int = 0,
) -> tuple[torch.Tensor, ContractionCounts]:
    """Evaluate a contraction by its plan.

    In the written order every input is aligned to all letters, the
    inputs are multiplied left to right, and the summed letters are
    summed at once. In an elimination each step multiplies the factors
    it joins over its bag, in the order they were made, and sums its
    letters away; the factors left are multiplied over the output. At a
    tie of a selective sum the derivative goes to the first best term of
    each sum the plan forms, so to the first best index in the order of
    elimination.

    Parameters
    ----------
    plan : ContractionPlan
        The plan.
    algebra : ContractionAlgebra
        The algebra the plan was made for.
    tensors : Sequence of torch.Tensor
        The inputs, each with its index axes in the order of its letters
        and then ``element_rank`` element axes.
    element_rank : int
        The number of trailing axes of one element of the algebra.

    Returns
    -------
    tuple of torch.Tensor and ContractionCounts
        The output, its index axes in the order of the output letters,
        and the work.

    Raises
    ------
    TypeError
        If an input is not a tensor.
    ValueError
        If the inputs do not fit the plan.
    """
    _check(plan, tensors, element_rank)
    tally = _Tally()
    universe = tuple(plan.extents)
    received = [
        _Factor(letters=tuple(letters), tensor=tensor, formed=False)
        for letters, tensor in zip(plan.inputs, tensors, strict=True)
    ]
    if plan.algorithm == "written order":
        total = _product(algebra, received, universe, element_rank, tally)
        axes = tuple(
            index for index, name in enumerate(universe) if name not in plan.output
        )
        if axes:
            total = _sum(algebra, total, axes, element_rank, tally)
        kept = [name for name in universe if name in plan.output]
        result = _Factor(letters=tuple(kept), tensor=total, formed=True)
        return _aligned(result, plan.output, element_rank), tally.counts()
    factors: dict[int, _Factor] = dict(enumerate(received))
    for number, step in enumerate(plan.steps):
        joined = [factors.pop(key) for key in step.factors]
        product = _product(algebra, joined, step.bag, element_rank, tally)
        for factor in joined:
            if factor.formed:
                tally.freed(_indices(factor.tensor, element_rank))
        axes = tuple(step.bag.index(name) for name in step.letters)
        reduced = _sum(algebra, product, axes, element_rank, tally)
        if len(joined) > 1:
            tally.freed(_indices(product, element_rank))
        factors[len(plan.inputs) + number] = _Factor(
            letters=tuple(name for name in step.bag if name not in step.letters),
            tensor=reduced,
            formed=True,
        )
    left = list(factors.values())
    total = _product(algebra, left, plan.output, element_rank, tally)
    return total, tally.counts()

fiber_join

fiber_join(algebra: ContractionAlgebra, values: Tensor, fibers: Sequence[Sequence[int]], zero: Tensor, axis: int = -1) -> Tensor

The sum of a table over each fiber of a map from one of its axes.

This is the contraction of the table with the graph of a map: entry p of the axis is summed into target q when p lies in fiber q. Every fiber is padded with the zero to the length of the largest, so one sum over a dense axis takes them all; the zero is the unit of the sum, so padding changes no value. The work is the number of targets times the largest fiber, never the table times the targets.

PARAMETER DESCRIPTION
algebra

The algebra.

TYPE: ContractionAlgebra

values

The table.

TYPE: Tensor

fibers

For each target, the entries of the axis it sums; each entry in at most one fiber.

TYPE: Sequence of Sequence of int

zero

The algebra's zero, of the table's shape with extent one on the axis.

TYPE: Tensor

axis

The axis mapped; the last by default.

TYPE: int DEFAULT: -1

RETURNS DESCRIPTION
Tensor

The table with the axis replaced by one of len(fibers) targets: the sum of each fiber, the zero for an empty one.

Source code in src/quivers/core/elimination.py
def fiber_join(
    algebra: ContractionAlgebra,
    values: torch.Tensor,
    fibers: Sequence[Sequence[int]],
    zero: torch.Tensor,
    axis: int = -1,
) -> torch.Tensor:
    """The sum of a table over each fiber of a map from one of its axes.

    This is the contraction of the table with the graph of a map: entry
    ``p`` of the axis is summed into target ``q`` when ``p`` lies in
    fiber ``q``. Every fiber is padded with the zero to the length of the
    largest, so one sum over a dense axis takes them all; the zero is the
    unit of the sum, so padding changes no value. The work is the number
    of targets times the largest fiber, never the table times the
    targets.

    Parameters
    ----------
    algebra : ContractionAlgebra
        The algebra.
    values : torch.Tensor
        The table.
    fibers : Sequence of Sequence of int
        For each target, the entries of the axis it sums; each entry in at
        most one fiber.
    zero : torch.Tensor
        The algebra's zero, of the table's shape with extent one on the
        axis.
    axis : int
        The axis mapped; the last by default.

    Returns
    -------
    torch.Tensor
        The table with the axis replaced by one of ``len(fibers)``
        targets: the sum of each fiber, the zero for an empty one.
    """
    axis = axis % values.dim()
    width = max((len(fiber) for fiber in fibers), default=0)
    padded = torch.cat([values, zero.to(values.dtype)], dim=axis)
    flat = [values.shape[axis]] * (len(fibers) * width)
    for target, fiber in enumerate(fibers):
        flat[target * width : target * width + len(fiber)] = list(fiber)
    index = torch.tensor(flat, dtype=torch.long, device=values.device)
    gathered = padded.index_select(axis, index)
    shape = (*values.shape[:axis], len(fibers), width, *values.shape[axis + 1 :])
    return algebra.join(gathered.reshape(shape), axis + 1)