Fast Einstein summation for the Wolfram Language
the syntax of numpy.einsum, indices repeated at will, optimal contraction orders, tensor-network diagrams
Website · Showcase · Manual · Guided tour · Wiki · Installation
Summa contracts tensors with the syntax of numpy.einsum: you write a contraction as on paper, the indices of every
factor, "ij,jk->ik", and Summa works out how to compute it — the cheapest order of the pairwise contractions and the
kernel of each, BLAS or vectorised, with no transposes, reshapes or intermediate arrays by hand. An index may appear in
any number of tensors — diagonals, traces, hyperedges, batch indices — and the network can be drawn as it is computed.
- Written as on paper, computed for you. The string syntax of numpy,
"ij,jk->ik", with implicit output, ellipsis and broadcasting, Unicode labels, or lists of labels of any kind; how to compute it is Summa's job. - Indices repeated at will. Diagonals, traces and sums, and an index shared by three or more tensors (hyperedges, batch indices) in a single call.
- The cheapest order. The order of the pairwise contractions minimises the flops (an exact search up to eight tensors,
greedy beyond);
EinsumPathgives its cost and its speed-up over the naive sum. - Fast kernels. Each contraction runs on BLAS
Dot, on batched kernels or on broadcasting, with as few transposes as possible; plans are cached, andEinsumFunctionprecompiles an einsum for loops. - The network, drawn.
EinsumDiagramdraws the tensor network — bonds, open legs, traces, hyperedges, the order of the contractions — andEinsumTreethe contraction tree with the cost of every step. - Any entries. Machine numbers, exact and symbolic entries, complex numbers,
SparseArray.
Every result is checked against numpy.einsum, and the optimal order against an exhaustive search of all orders.
Everything it does, with the names of the functions
Einsum[spec, t1, t2, ...], withspeca numpy string ("ij,jk->ik","...ij,...jk->...ik") or a rule of lists of labels ({{i, j}, {j, k}} -> {i, k}); options"Path"(Automatic,"Optimal","Greedy","Sequential"or a list of pairs),"BatchMethod"(Automatic,"Dot","Vectorized"),"Cache"EinsumPath[spec, t1, ...]orEinsumPath[spec, {dims1, ...}]: the order of the contractions, its flops, the naive flops, the speed-up and the largest intermediateEinsumFunction[spec, {dims1, ...}]: a precompiled einsum for fixed shapes, with the properties"Path","Flops","Speedup","Diagram","Tree", ...EinsumDiagram[spec],EinsumDiagram[spec, t1, ...]: the tensor network; options"ShowPath","Steps","Layout","TensorNames","Highlight","ShowDimensions"EinsumTree[spec, t1, ...]: the contraction tree, with the indices and the flops of every intermediateEinsumClearCache[];$SummaVersion,SummaUpdateCheck[],$SummaUpdateCheck
One session, from a trace to a tensor network:
Needs["Summa`"]Indices as on paper. A repeated index is summed: the trace of a matrix, and its square.
m = {{a, b}, {c, d}};
{Einsum["ii", m], Einsum["ij,jk->ik", m, m]}An index in any number of tensors. ResourceFunction["EinsteinSummation"] refuses an index that appears three
times, and TensorContract sums one only after building the whole outer product. In Summa an index may appear in any
number of tensors: here i is shared by three vectors,
Einsum["i,i,i->", {a, b}, {c, d}, {e, f}]and in "ai,bi,ci->abc" by three matrices, the reconstruction of a tensor from its canonical decomposition: a hyperedge,
drawn by EinsumDiagram.
EinsumDiagram["ai,bi,ci->abc"]A Kubo formula, as it is written. The optical conductivity of a two-band chain,
h[k_] := (1 + 0.6 Cos[k]) PauliMatrix[1] + 0.6 Sin[k] PauliMatrix[2] + 0.4 PauliMatrix[3]; (* the Rice-Mele chain *)
ks = Most[Subdivide[-Pi, Pi, 400]]; ws = Subdivide[0.5, 4., 350];
{e, u} = Transpose[Eigensystem /@ (h /@ ks)];
current = MapThread[Conjugate[#1] . (D[h[q], q] /. q -> #2) . Transpose[#1] &, {u, ks}];
f = UnitStep[-e]; (* half filling *)
weight = Table[If[n == m, 0, (f[[q, n]] - f[[q, m]])/(e[[q, m]] - e[[q, n]])/(w - e[[q, m]] + e[[q, n]] + 0.05 I)],
{q, 400}, {n, 2}, {m, 2}, {w, ws}];
sigma = I/400 Einsum["knm,kmn,knmw->w", current, current, weight];
ListLinePlot[Transpose[{ws, Re[sigma]}], AxesLabel -> {"\[Omega]", "Re \[Sigma]"}]A tensor network. The norm of a matrix-product state of four sites, the state above and its conjugate below:
mps = "pa,aqb,brc,cs,pA,AqB,BrC,Cs->";
EinsumDiagram[mps]The order matters. With bonds of dimension 32, the order that Summa chooses costs
dims = {{2, 32}, {32, 2, 32}, {32, 2, 32}, {32, 2}, {2, 32}, {32, 2, 32}, {32, 2, 32}, {32, 2}};
Lookup[EinsumPath[mps, dims], {"Flops", "NaiveFlops", "Speedup"}]EinsumTree[mps, dims]Fast in loops. EinsumFunction plans once for fixed shapes: here a thousand products of 4×4 matrices, a batched
kernel instead of a thousand calls to Dot.
SeedRandom[1]; {x, y} = RandomReal[1, {2, 1000, 4, 4}];
batch = EinsumFunction["bij,bjk->bik", {{1000, 4, 4}, {1000, 4, 4}}];
batch[x, y] == MapThread[Dot, {x, y}]True
Next. The guided tour goes through the syntax, repeated indices, orders and kernels step by step; the
wiki has the recipes; the
showcase shows what the package can do and the
manual describes every function. ?Summa`* lists the
functions and ?Name explains each one.
Install the paclet of the latest release once:
PacletInstall["https://github.com/n4sd4q/Summa/releases/download/v1.0.0/Summa-1.0.0.paclet"]and load it in every session:
Needs["Summa`"]There are no dependencies; the package needs Mathematica 12.1 or later. The guided tour, a notebook to run cell by cell, comes with the paclet:
NotebookOpen[PacletObject["Summa"]["AssetLocation", "Examples"]]In a notebook the package looks for a newer release on GitHub once a day; $SummaUpdateCheck = False before Needs turns
this off (SECURITY.md says more). Other ways to install, and updating: the wiki's
Installation page.
| Document | Contents |
|---|---|
| Website | the package at a glance: what it does, the first example, installation, the documents |
| Guided tour | a notebook to run cell by cell, from a trace to tensor networks (Summa/Examples.nb in the paclet) |
| Wiki | practical guides: the syntax, repeated indices, orders and costs, speed, the diagrams; a FAQ |
| Showcase (PDF) | the package step by step, from the syntax to tensor networks, with the cost of every order |
| Manual (PDF) | every function, option and message, the conventions and the limits |
| Changelog | what changed in each version |
Every output printed in the documents is computed by the code shown before it.
The tests (wolfram -script Tests/RunTests.wls, 735 tests) compare Einsum with numpy.einsum on 213 contractions
computed in exact integer arithmetic, every one with every order and every kernel, and with an explicit sum in machine
precision, real and complex; the optimal order must cost as little as an exhaustive search of all orders on 40 networks.
sh Development/check_docs.sh runs the code of the showcase, the manual, the guided tour, the README and the wiki again,
in fresh kernels, and compares it with what they print.
numpy.einsum defines the syntax, and
opt_einsum the search of the contraction order;
TensorOperations.jl (Julia) and
cotengra (Python, large networks) do the same in other languages. In Mathematica,
TensorContract and ResourceFunction["EinsteinSummation"] contract pairs of indices. Summa brings the syntax of numpy to the
Wolfram Language with indices shared by any number of tensors, the optimal order, BLAS and batched kernels, and the drawing
of the network.
If you use Summa in published work, please cite it as described in CITATION.cff.
Released under the GNU General Public License, version 3 or later, with two additional terms
(NOTICE): the attribution to the author must be kept, and modified versions must say that they are modified,
by whom and when. Author: Nazzareno Africani (SISSA).




