Skip to content

Wiring

A wiring is an einsum string that says which tensor axes denote the same index and which remain in the result. In ij,jk->ik, j is summed out and i and k survive. The wiring fixes the shape, and the composition rule fixes whether summing out means a sum, a minimum, or another reduction. Einsum wiring thus extends binary composition to contractions of any number of tensors. These contractions form an algebra of wiring diagrams only when that algebra's equations hold (Spivak, 2013; Vagner et al., 2015).

wiring

N-ary tensor contractions specified by shared axis names.

A CompositionRule defines binary composition: (f >> g)[i, k] = ⋁_j f[i, j] ⊗ g[j, k]. A wiring rule can instead combine several tensors in one contraction, for instance:

out[s, c] = ⋁_{p, q} (
    arg1[s, p] ⊗ arg2[s, q] ⊗ kernel[p, q, c]
)

Here s remains shared by both arguments, while p and q are eliminated. Expressing this through binary composition would also require operations that arrange, copy, or pair the interfaces; plain chaining alone does not describe that wiring.

WiringRule pairs a CompositionRule, which supplies tensor_op and join, with an einsum-style specification of the axes to retain or reduce. EinsumWiring evaluates it by the plans of quivers.core.elimination: variable elimination when the rule establishes the laws of a commutative semiring, the written order otherwise. CONTRACTION_WORK and WRITTEN_ORDER_WORK are the cost claims of the two, and EinsumWiring.apply_with_work measures the counters they bound. Wiring diagrams and operads provide a mathematical account of how compatible interfaces connect Vagner et al. (2015). Interpreting these contractions as operations of an operad requires the relevant composition laws, including the compatibility of tensor products and reductions. A runtime wiring specification alone does not establish those laws.

CONTRACTION_MEASURES module-attribute

CONTRACTION_MEASURES: tuple[WorkField, ...] = measuring({WorkField.SCALAR_SUMS, WorkField.SCALAR_PRODUCTS, WorkField.SCALAR_DIVISIONS, WorkField.STAR_PIVOTS, WorkField.EXACT_OPERATIONS, WorkField.KEY_COMPARISONS, WorkField.HASH_OPERATIONS, WorkField.ELEMENTS_ALLOCATED, WorkField.PEAK_LIVE_ELEMENTS})

The counters a contraction measures.

CONTRACTION_WORK module-attribute

CONTRACTION_WORK = ComplexityClaim(query='contraction of a tensor network over a commutative semiring', parameters=(ComplexityParameter(name='k', meaning='inputs'), ComplexityParameter(name='s', meaning='letters summed out'), ComplexityParameter(name='W', meaning='elements of the largest bag of the chosen order, or of the output when that is larger')), model=ALGEBRA_OPERATIONS, bounds=(ComplexityBound(phase=Phase.EXECUTION, resource='time', expression='(k + s) W', status=Conditional(hypothesis='the exponential time hypothesis: for classes of bounded arity no algorithm beats treewidth by more than a logarithmic factor in the exponent', sources=(_FAQ, _DECHTER, _MARX))), ComplexityBound(phase=Phase.EXECUTION, resource='space', expression='(s + 1) W', status=Conditional(hypothesis='as for time', sources=(_FAQ, _DECHTER))), ComplexityBound(phase=Phase.DIFFERENTIATION, resource='time', expression='(k + s) W', status=Conditional(hypothesis='as for execution; a gradient costs a constant times it', sources=(_FAQ, _BAUR_STRASSEN))), ComplexityBound(phase=Phase.DIFFERENTIATION, resource='space', expression='(k + s) W', status=Conditional(hypothesis='the autograd tape holds the operands of every product', sources=(_FAQ,)))), inapplicable=(PhaseInapplicable(phase=Phase.CONSTRUCTION, reason='the order is chosen from the letters and their extents, in time polynomial in the letters and independent of the values'), PhaseInapplicable(phase=Phase.REFIT, reason='a refit is one more contraction; the plan of the extents is kept')), conditions=("every law of ELIMINATION_LAWS established by the algebra's own claims", 'the order is greedy by the elements of each bag and is recorded with its widths; an order of least width is NP-hard to find and is not claimed', 'at a tie of a selective sum the derivative goes to the first best index in the order of elimination'))

The cost of a contraction by variable elimination.

WRITTEN_ORDER_WORK module-attribute

WRITTEN_ORDER_WORK = ComplexityClaim(query='contraction of a tensor network over an algebra without those laws', parameters=(ComplexityParameter(name='k', meaning='inputs'), ComplexityParameter(name='U', meaning='the product of the extents of every letter')), model=ALGEBRA_OPERATIONS, bounds=tuple(ComplexityBound(phase=phase, resource=resource, expression=expression, status=Unresolved(obligation='whether fewer operations suffice: the algebra establishes no law that moves a sum inside a product, so the written expression is evaluated as it is defined')) for phase, resource, expression in _WRITTEN_BOUNDS), inapplicable=(PhaseInapplicable(phase=Phase.CONSTRUCTION, reason='the written order is read off the specification'), PhaseInapplicable(phase=Phase.REFIT, reason='a refit is one more contraction')), conditions=('the inputs are multiplied left to right in written order, then every contracted letter is summed at once, as the contraction is defined',))

The cost of a contraction in the written order.

WiringRule

Bases: ABC

An n-ary morphism contraction under a fixed CompositionRule.

Generalizes binary composition >> to arbitrary-arity tensor networks. A WiringRule carries:

  • a composition_rule whose tensor_op and join drive the contraction;
  • a wiring specification that names which axes of which inputs participate in which contractions, and which axes survive to the output.

Subclasses implement apply to perform the contraction given a list of input tensors.

composition_rule abstractmethod property

composition_rule: CompositionRule

The underlying binary composition rule of this contraction.

RETURNS DESCRIPTION
CompositionRule

The enriching algebra.

input_arity abstractmethod property

input_arity: int

Number of input tensors this wiring expects.

RETURNS DESCRIPTION
int

The number of inputs.

name property

name: str

The class name.

RETURNS DESCRIPTION
str

The name.

apply abstractmethod

apply(*tensors: Tensor) -> Tensor

Run the contraction on the given input tensors.

PARAMETER DESCRIPTION
*tensors

The inputs.

TYPE: Tensor DEFAULT: ()

RETURNS DESCRIPTION
Tensor

The contraction.

Source code in src/quivers/core/wiring.py
@abstractmethod
def apply(self, *tensors: torch.Tensor) -> torch.Tensor:
    """Run the contraction on the given input tensors.

    Parameters
    ----------
    *tensors : torch.Tensor
        The inputs.

    Returns
    -------
    torch.Tensor
        The contraction.
    """

__repr__

__repr__() -> str

The class name and arity.

RETURNS DESCRIPTION
str

The representation.

Source code in src/quivers/core/wiring.py
def __repr__(self) -> str:
    """The class name and arity.

    Returns
    -------
    str
        The representation.
    """
    return f"{type(self).__name__}(arity={self.input_arity})"

EinsumWiring

EinsumWiring(composition_rule: CompositionRule, spec: str)

Bases: WiringRule

A multi-input contraction specified by an einsum-style string.

Spec syntax::

"input_1, input_2, ..., input_n -> output"

where each input_i and output is a sequence of axis letters identifying which dimensions of that tensor align. Axes that appear in some input but not in the output are contracted (reduced via the composition rule's join); axes that appear in the output are preserved (broadcast as needed).

Examples::

EinsumWiring(product_fuzzy, "ij, jk -> ik")
    # binary composition: contract over j, preserve (i, k)
EinsumWiring(product_fuzzy, "sp, sq, pqo -> so")
    # ternary contraction: two argument tensors over
    # (s, *) and a kernel contracted over (p, q),
    # preserving (s, o)

How the contraction is evaluated is fixed by quivers.core.elimination.plan_contraction from the rule's law claims and the extents of the inputs, and recorded as a quivers.core.elimination.ContractionPlan. A rule that establishes every law of quivers.core.elimination.ELIMINATION_LAWS is contracted by variable elimination, with the cost of CONTRACTION_WORK; any other rule is evaluated in the written order, with the cost of WRITTEN_ORDER_WORK: every input is aligned to all letters, the inputs are folded left to right with tensor_op, and the contracted letters are reduced at once with join. A rule whose elements have axes of their own, such as a quivers.core.algebras.MatrixSemiring, keeps them last in every tensor.

PARAMETER DESCRIPTION
composition_rule

The rule supplying tensor_op and join.

TYPE: CompositionRule

spec

The einsum specification.

TYPE: str

RAISES DESCRIPTION
TypeError

If composition_rule is not a CompositionRule.

ValueError

If the specification is malformed.

Parse and check a specification.

PARAMETER DESCRIPTION
composition_rule

The rule supplying tensor_op and join.

TYPE: CompositionRule

spec

The einsum specification.

TYPE: str

RAISES DESCRIPTION
TypeError

If composition_rule is not a CompositionRule.

ValueError

If the specification has no arrow, an empty input, a letter repeated within an input or the output, or an output letter in no input.

Source code in src/quivers/core/wiring.py
def __init__(self, composition_rule: CompositionRule, spec: str) -> None:
    """Parse and check a specification.

    Parameters
    ----------
    composition_rule : CompositionRule
        The rule supplying ``tensor_op`` and ``join``.
    spec : str
        The einsum specification.

    Raises
    ------
    TypeError
        If ``composition_rule`` is not a `CompositionRule`.
    ValueError
        If the specification has no arrow, an empty input, a letter
        repeated within an input or the output, or an output letter in
        no input.
    """
    if not isinstance(composition_rule, CompositionRule):
        raise TypeError(
            f"EinsumWiring: composition_rule must be a CompositionRule, "
            f"got {type(composition_rule).__name__}"
        )
    if "->" not in spec:
        raise ValueError(f"EinsumWiring: spec must contain '->', got {spec!r}")
    lhs, rhs = spec.split("->", maxsplit=1)
    input_specs = tuple(s.strip() for s in lhs.split(","))
    output_spec = rhs.strip()
    # A letter repeated within one input would denote a diagonal or a
    # trace, which no contraction here evaluates, so it is refused when
    # the wiring is built.
    for i, ispec in enumerate(input_specs):
        if not ispec:
            raise ValueError(f"EinsumWiring: input {i} of spec {spec!r} is empty")
        if len(set(ispec)) != len(ispec):
            raise ValueError(
                f"EinsumWiring: input {i} of spec {spec!r} repeats "
                f"an axis letter ({ispec!r}); diagonal/trace "
                f"contractions are not supported by this wiring"
            )
    if len(set(output_spec)) != len(output_spec):
        raise ValueError(
            f"EinsumWiring: output {output_spec!r} of spec "
            f"{spec!r} repeats an axis letter"
        )
    letters = set("".join(input_specs))
    for ch in output_spec:
        if ch not in letters:
            raise ValueError(
                f"EinsumWiring: output letter {ch!r} not present "
                f"in any input of spec {spec!r}"
            )
    self._rule = composition_rule
    self._spec = spec
    self._input_specs = input_specs
    self._output_spec = output_spec
    self._rank = (
        len(composition_rule.element_shape)
        if isinstance(composition_rule, Carrier)
        else 0
    )
    self._plans: dict[tuple[tuple[str, int], ...], ContractionPlan] = {}

composition_rule property

composition_rule: CompositionRule

The rule of the contraction.

RETURNS DESCRIPTION
CompositionRule

The rule.

input_arity property

input_arity: int

The number of inputs.

RETURNS DESCRIPTION
int

One per input specification.

spec property

spec: str

The specification as written.

RETURNS DESCRIPTION
str

The specification.

input_specs property

input_specs: tuple[str, ...]

The letters of each input.

RETURNS DESCRIPTION
tuple of str

One string per input.

output_spec property

output_spec: str

The letters of the output.

RETURNS DESCRIPTION
str

The output letters.

complexity property

complexity: ComplexityClaim

The cost claim of the contraction under its rule.

RETURNS DESCRIPTION
ComplexityClaim

CONTRACTION_WORK when the rule establishes every law of quivers.core.elimination.ELIMINATION_LAWS, else WRITTEN_ORDER_WORK.

plan

plan(extents: Mapping[str, int]) -> ContractionPlan

The plan for given extents, made once per extents.

PARAMETER DESCRIPTION
extents

The extent of every letter.

TYPE: Mapping of str to int

RETURNS DESCRIPTION
ContractionPlan

The plan.

RAISES DESCRIPTION
ValueError

If a letter has no extent of at least zero.

Source code in src/quivers/core/wiring.py
def plan(self, extents: Mapping[str, int]) -> ContractionPlan:
    """The plan for given extents, made once per extents.

    Parameters
    ----------
    extents : Mapping of str to int
        The extent of every letter.

    Returns
    -------
    ContractionPlan
        The plan.

    Raises
    ------
    ValueError
        If a letter has no extent of at least zero.
    """
    key = tuple(
        (name, int(extents[name]) if name in extents else -1)
        for name in dict.fromkeys("".join(self._input_specs))
    )
    found = self._plans.get(key)
    if found is None:
        found = plan_contraction(
            self._rule, self._input_specs, self._output_spec, extents
        )
        self._plans[key] = found
    return found

apply_with_work

apply_with_work(*tensors: Tensor) -> tuple[Tensor, WorkReport]

Run the contraction and count its work.

PARAMETER DESCRIPTION
*tensors

The inputs, in the order of the specification.

TYPE: Tensor DEFAULT: ()

RETURNS DESCRIPTION
tuple of torch.Tensor and WorkReport

The output, its axes in the order of the output letters, and the work of execution in elements of the algebra.

RAISES DESCRIPTION
TypeError

If an input is not a tensor.

ValueError

If the inputs do not fit the specification.

Source code in src/quivers/core/wiring.py
def apply_with_work(
    self, *tensors: torch.Tensor
) -> tuple[torch.Tensor, WorkReport]:
    """Run the contraction and count its work.

    Parameters
    ----------
    *tensors : torch.Tensor
        The inputs, in the order of the specification.

    Returns
    -------
    tuple of torch.Tensor and WorkReport
        The output, its axes in the order of the output letters, and
        the work of execution in elements of the algebra.

    Raises
    ------
    TypeError
        If an input is not a tensor.
    ValueError
        If the inputs do not fit the specification.
    """
    plan = self.plan(self._extents(tensors))
    value, counts = run_contraction(plan, self._rule, tensors, self._rank)
    return value, contraction_report(counts)

apply

apply(*tensors: Tensor) -> Tensor

Run the contraction.

PARAMETER DESCRIPTION
*tensors

The inputs, in the order of the specification.

TYPE: Tensor DEFAULT: ()

RETURNS DESCRIPTION
Tensor

The output, its axes in the order of the output letters.

RAISES DESCRIPTION
TypeError

If an input is not a tensor.

ValueError

If the inputs do not fit the specification.

Source code in src/quivers/core/wiring.py
def apply(self, *tensors: torch.Tensor) -> torch.Tensor:
    """Run the contraction.

    Parameters
    ----------
    *tensors : torch.Tensor
        The inputs, in the order of the specification.

    Returns
    -------
    torch.Tensor
        The output, its axes in the order of the output letters.

    Raises
    ------
    TypeError
        If an input is not a tensor.
    ValueError
        If the inputs do not fit the specification.
    """
    return self.apply_with_work(*tensors)[0]

contraction_report

contraction_report(counts: ContractionCounts) -> WorkReport

The work of a contraction as a work report of its execution.

PARAMETER DESCRIPTION
counts

The counts.

TYPE: ContractionCounts

RETURNS DESCRIPTION
WorkReport

Sums, products, elements formed and the largest number held, each measured; a contraction divides, pivots, compares and hashes nothing, which is measured as zero.

Source code in src/quivers/core/wiring.py
def contraction_report(counts: ContractionCounts) -> WorkReport:
    """The work of a contraction as a work report of its execution.

    Parameters
    ----------
    counts : ContractionCounts
        The counts.

    Returns
    -------
    WorkReport
        Sums, products, elements formed and the largest number held, each
        measured; a contraction divides, pivots, compares and hashes
        nothing, which is measured as zero.
    """
    return WorkReport(
        phase=Phase.EXECUTION,
        scalar_sums=counts.sums,
        scalar_products=counts.products,
        elements_allocated=counts.allocated,
        peak_live_elements=counts.peak,
        measured=CONTRACTION_MEASURES,
    )

einsum_wiring

einsum_wiring(composition_rule: CompositionRule, spec: str) -> EinsumWiring

Convenience constructor for EinsumWiring.

PARAMETER DESCRIPTION
composition_rule

The rule supplying tensor_op and join.

TYPE: CompositionRule

spec

An einsum specification such as "ij,jk->ik".

TYPE: str

RETURNS DESCRIPTION
EinsumWiring

The wiring rule for spec.

RAISES DESCRIPTION
TypeError

If composition_rule is not a CompositionRule.

ValueError

If spec is malformed.

Source code in src/quivers/core/wiring.py
def einsum_wiring(composition_rule: CompositionRule, spec: str) -> EinsumWiring:
    """Convenience constructor for `EinsumWiring`.

    Parameters
    ----------
    composition_rule : CompositionRule
        The rule supplying ``tensor_op`` and ``join``.
    spec : str
        An einsum specification such as ``"ij,jk->ik"``.

    Returns
    -------
    EinsumWiring
        The wiring rule for ``spec``.

    Raises
    ------
    TypeError
        If ``composition_rule`` is not a `CompositionRule`.
    ValueError
        If ``spec`` is malformed.
    """
    return EinsumWiring(composition_rule, spec)

contract

contract(rule: WiringRule, *tensors: Tensor) -> Tensor

Apply a WiringRule to a sequence of input tensors.

Thin wrapper around WiringRule.apply for call-site readability::

result = contract(my_rule, arg1, arg2, kernel)

is an alternative to the method-call form.

PARAMETER DESCRIPTION
rule

The wiring rule to apply.

TYPE: WiringRule

*tensors

The input tensors, in the order the rule expects.

TYPE: Tensor DEFAULT: ()

RETURNS DESCRIPTION
Tensor

The contracted tensor.

Source code in src/quivers/core/wiring.py
def contract(
    rule: WiringRule,
    *tensors: torch.Tensor,
) -> torch.Tensor:
    """Apply a `WiringRule` to a sequence of input tensors.

    Thin wrapper around `WiringRule.apply` for call-site
    readability::

        result = contract(my_rule, arg1, arg2, kernel)

    is an alternative to the method-call form.

    Parameters
    ----------
    rule : WiringRule
        The wiring rule to apply.
    *tensors : torch.Tensor
        The input tensors, in the order the rule expects.

    Returns
    -------
    torch.Tensor
        The contracted tensor.
    """
    return rule.apply(*tensors)

Cited sources

David I. Spivak. The Operad of Wiring Diagrams: Formalizing a Graphical Language for Databases, Recursion, and Plug-and-Play Circuits. 2013. arXiv:1305.0297, doi:10.48550/arXiv.1305.0297.

Dmitry Vagner, David I. Spivak, and Eugene Lerman. Algebras of Open Dynamical Systems on the Operad of Wiring Diagrams. Theory and Applications of Categories, 30(51):1793–1822, 2015. URL: https://www.tac.mta.ca/tac/volumes/30/51/30-51abs.html.