Architecture Overview#

This page is for readers who want to know how Einsums is put together, how the modules depend on each other, what happens when you call einsum, and where the ComputeGraph and the Python bindings sit relative to the rest. If you just want to use Einsums, start with the Absolute Beginner’s Guide and the tutorials instead.

Layered design#

Einsums is organized as a stack of modules, each with a single responsibility and an explicit set of dependencies. The build refuses cycles: every module declares its dependencies in CMake, and adding a new one means following the established direction of the arrows below.

┌────────────────────────────────────┐  ┌──────────────────────────┐
│  ComputeGraph                      │  │  TensorAlgebra           │
│  (string einsum dispatch and its   │  │  (compile-time Indices{} │
│   generic loop, deferred IR,       │  │   einsum and its         │
│   passes, executors, distributed   │  │   generic loop)          │
│   expansion)                       │  │                          │
└────────────────┬───────────────────┘  └──────────────┬───────────┘
                 │                                     │
                 └──────────────────┬──────────────────┘
                                    │
                 ┌──────────────────┴──────────────────┐
                 │                                     │
        ┌────────▼────────┐                  ┌─────────▼─────────┐
        │  LinearAlgebra  │                  │    PackedGemm     │
        │  (gemm, syev,   │                  │   (BLIS-style     │
        │   invert, ...)  │                  │   pack-and-tile)  │
        └────────┬────────┘                  └─────────┬─────────┘
                 │                                     │
                 └──────────────────┬──────────────────┘
                                    │
                 ┌──────────────────▼──────────────────┐
                 │   BLAS  (Einsums-level API)         │
                 └──────────────────┬──────────────────┘
                 ┌──────────────────▼──────────────────┐
                 │   BLASVendor  (MKL / OpenBLAS /     │
                 │                Accelerate)          │
                 └──────────────────┬──────────────────┘
                 ┌──────────────────▼──────────────────┐
                 │   BLASBase  (types, ABI)            │
                 └─────────────────────────────────────┘

The leaf modules wrap the moving parts of the hardware target. Everything above them is portable C++20 that targets the Einsums-level abstractions, not the vendor primitives directly.

The dispatch flow#

An einsum names its operands’ axes with a string spec, and the engine in ComputeGraph/StringDispatch.hpp routes each call to the most specialized backend that can take the contraction’s index pattern. The spec is data, not types: the route is chosen when the call runs, which is what lets a graph pass rewrite a spec and Python hand one through unchanged.

When you write

cg::einsum("ij <- ik ; kj", &C, A, B);

the dispatcher:

  1. Parses the spec into index lists (i, j on C, i, k on A, k, j on B).

  2. Classifies them into groups: the M axes appear only in the target and A, the N axes appear only in the target and B, the K axes are shared links, and the batch axes are shared targets.

  3. Takes the first route that fits:

    • Nothing, or only the scaling of C, when an extent is zero.

    • A strided view, when a letter repeats within one operand (a diagonal): the operand is read with one axis per distinct letter, and the contraction continues down this list.

    • A sum over one operand first, when a letter appears in that operand alone (a trace): the operand is summed over it into a temporary, and the smaller contraction continues down this list.

    • Vendor BLAS, when the pattern is a plain dot, gemv, ger or gemm, or an elementwise product. It uses the transposition flags BLAS offers, and copies no operand, except that an elementwise product permutes an operand whose letters are the target’s in another order.

    • PackedGemm for arbitrary-rank contractions that don’t fit a stock BLAS call. It either hands the whole contraction to a vendor gemm whose strides happen to fit, or runs its own BLIS-style packed loops over a register-blocked micro-kernel. It may also decline, in which case the generic loop takes the contraction.

    • A generic nested loop as the last resort.

For the example above the dispatcher sees ij = ik * kj and matches a pure dgemm: one cblas_dgemm call on the operands’ own strides.

When the dispatcher can’t match a stock BLAS shape, for example ijl = ik * kjl, it goes to PackedGemm, and what happens there is decided from the plan and the machine.

Inside a ComputeGraph the spec is parsed once, when the call is captured, into a node the optimization passes can read and rewrite. The route is chosen again each time the graph runs, since a pass may have changed the spec or the operands in between.

The compile-time-index form, tensor_algebra::einsum with Indices{...}, remains for eager code written against it; ComputeGraph and the Python bindings use the string form. It chooses its route when the template instantiates, and walks much the same ladder.

Planning#

try_packed_gemm builds a ContractionSpec from the index letters and derives a PackingPlan, which records the M / N / K / batch dimension groups and each group’s stride in each tensor. Plans are memoized in a process-wide PackingPlanCache keyed by a ContractionKey; a repeated call on a graph node can go further and carry a ContractionSite, which caches the resolved plan on the node so a hit skips the key build and the cache lookup entirely.

PackedGemm can also decline, and a decline is memoized like any other outcome so later identical calls turn away immediately. The cases:

  • the packing topology doesn’t fit the contraction pattern at all;

  • a letter summed out of one operand alone, which has no axis in the plan;

  • a plain single-M/N/K matrix product, which a direct gemm takes instead;

  • an outer-product-shaped contraction below 768 M × N elements, where the generic loop measures faster;

  • on the compile-time Indices{} path only, a batch-dot or GEMV-shaped contraction, and a scatter-layout shape where the caller has a TTGT (Sort+GEMM) fallback and this CPU’s kernel does not beat it, which includes every batched scatter shape.

Execution#

Before planning, a GEMV-shaped contraction whose operand interleaves its output and summed axes, so that no matrix view of it exists, takes the stream route: one pass over that operand in storage order. Otherwise, once a plan is accepted, blis_contraction runs it by one of the routes below, named by packed_gemm::last_contraction_route():

gemm_batch

A batched shape whose per-slice strides map onto a stock GEMM. Builds the pointer arrays and makes a single blas::gemm_batch call.

flatten_gemm, flatten_gemm_hptt, flatten_gemm_hptt_chunked, flatten_gemm_gather

Multi-K with a non-scatter C. Makes A and B contiguous M × K and K × N buffers and calls vendor gemm. The suffix says how: already flat, transposed by HPTT (in chunks under --einsums:packed-gemm:flatten-budget), or gathered.

gemm_k_loop

Multi-K where flattening would transpose an operand whole. Holds every K dimension but one fixed and runs a loop of strided GEMMs accumulating into C, with no copy.

single_k_gemm

A single-K slice whose strides already describe a GEMM. Called directly, with no packing at all.

packed

The engine’s own loops. Packs A and B into cache-blocked panels, MC × KC and KC × NC, sized by compute_blocking from the detected L1, L2, and L3 (one column of packed A in L1, the A panel in half the L2, the B panel in half the L3), then contracts each block one of two ways depending on the resolved kernel’s MicroKernelShape::block_gemm: either the rung’s own MR × NR register-blocked micro-kernel, or one vendor gemm per cache block into a contiguous temporary followed by a scatter into C. The second wins where the vendor library reaches matrix hardware the tile kernel cannot, such as Accelerate’s AMX; the first wins where the tile kernel is the better path, such as the SME rung’s FMOPA tiles.

Every route but packed and stream hands the contraction to the vendor. That is usually what you want, but not always: a caller holding a node-scoped thread width has its vendor calls clamped to one thread, so those routes would run the node serially while the packed loops would fork from the same ICV the width raised. blis_contraction checks blas::vendor_call_is_fenced() and prefers the packed loops when it is set. gemm_batch is exempt, since its vendor entry point is Einsums’ own OpenMP loop over serial GEMMs and carries no fence.

Micro-kernels and SIMD rungs#

The micro-kernel bodies are compiled once per instruction-set rung by Stripes’ stripes_add_dispatch_sources(), each copy in its own namespace, and the rung is chosen at run time in MicroKernelDispatch.cpp by walking the architecture’s preference order (v4, v3, v2, baseline on x86; sme, baseline on aarch64) from stripes::selected_arch() and taking the first rung that was built and that the machine supports. The result is cached per element type. micro_kernel_entry<T>() and micro_kernel_shape<T>() resolve through the same ladder, which is what keeps the packing geometry matched to the kernel that will consume it: the SSE, AVX, AVX-512 and NEON rungs pack to a tile of two of the rung’s own vectors along M by six columns (an AVX2 rung is 16 by 6 for float and 8 by 6 for double), and the cache blocks are derived from that tile; the SME rung packs to ZA-tile blocking and raises KC so its accumulators hold the C block across the whole K loop. The tile is a compile-time fact of each rung’s translation unit, not of the flags the library as a whole was built with, which is what lets a distribution build compiled for SSE2 run full-width kernels on the machine it lands on.

Complex types reuse the real kernels rather than needing their own. On the tile path that is Van Zee’s 1m method, where A packs in expanded 1e form and B packs real and imaginary parts as adjacent K rows so the real kernel writes interleaved-complex output directly. On the block-GEMM path it is the 3m (Karatsuba) method, three real GEMMs per block instead of one complex GEMM, which is 25% fewer flops and reaches real-only matrix hardware, at the cost of mildly weaker error bounds than conventional complex multiplication.

Inspecting a decision#

Raising the log level to INFO (--einsums:log:level 2) reports two of the declines described above, an invalid packing topology and the deferral to Sort+GEMM, and not the accepted plans. To see what actually ran, ask for it directly: compute_graph::dispatch::last_dispatch_route() names the route the last einsum on this thread took.

cg::einsum("ij <- ik ; kj", &C, A, B);
std::string const route = cg::dispatch::last_dispatch_route(); // "gemm_direct_runtime"

One level down, packed_gemm::last_contraction_route() names which of the routes above PackedGemm took. Both are thread-local and exist for test introspection, not for steering execution; the test suite asserts on them so that a silent fall back to the generic loop cannot pass unnoticed.

Every decision is also annotated into the profile, under packed_gemm_skip for a decline and packed_gemm_path for an accepted plan.

The ComputeGraph layer#

Above the eager-dispatch layer sits the ComputeGraph. This is an optional deferred-execution intermediate representation. Capture a sequence of operations into a einsums::compute_graph::Graph, run optimization passes over it, then execute. The model is the same idea as CUDA Graphs or PyTorch FX, but the passes are tensor-algebra aware and integrate with the distribution layer.

Two execution modes coexist:

  • In eager mode, every call dispatches and runs immediately. It is simple and well suited to ad-hoc work and tutorials, and it is what every example in the beginner’s guide uses.

  • In deferred mode, calls inside a capture block become graph nodes instead of running. After capture, pass managers can rewrite the graph. This includes fusing adjacent operations, eliminating dead nodes, creating shared common intermediates, planning memory reuse, folding linear combinations of contractions, creating partitions for distributed execution, and scheduling communication. Then g.execute() walks the optimized DAG with whichever executor you pick: sequential, OpenMP, or dataflow (on the TaskPool).

The passes that ship today include common-subexpression elimination, dead-node elimination, reordering for register reuse, memory planning, chain-parenthesization, scale absorption, element-wise fusion, loop-invariant hoisting, linear-combination contraction folding, plus the distributed-execution passes mentioned below.

You don’t have to use the graph. But if you’re running a coupled-cluster inner loop, an SCF cycle, or any iteration that touches the same handful of tensors hundreds of times, capturing once and executing many times gets you whole-algorithm rewrites for free that no per-call dispatcher could see.

Tensor types#

Einsums has several tensor types, each with a different tradeoff between flexibility and compile-time information.

  • einsums::Tensor is the workhorse: rank fixed at compile time, scalar type fixed at compile time, owns its data, dense and contiguous, and column-major by default. When you write Tensor<double, 2> A("A", 100, 100) the compiler knows the rank and data type; an einsum on it still chooses its route at run time, on a rank-erased view.

  • einsums::TensorView is a non-owning window onto another tensor with explicit strides. Use it to grab a sub-block, a column, a strided slice, or to alias the same buffer with a different shape.

  • RuntimeTensor carries its rank and dtype as runtime values. Use it when those can’t be known at compile time. For example, the Python bindings always go through RuntimeTensor because Python doesn’t have C++ templates.

  • einsums::BlockTensor is a block-diagonal sparse variant, and einsums::TiledTensor is a tiled variant for cache-friendly access on operations that walk the matrix in blocks. The Python surface supports the dense types and TiledRuntimeTensor.

  • einsums::DiskTensor (in TensorIO) stores its data in HDF5 format on a mass storage device rather than RAM. Use it for working sets that are too large to live in memory, combined with tensor_io::Slab to schedule slab-by-slab reads and writes through the ComputeGraph.

The einsum engine and the graph executors are written against rank-erased views. A compile-time-typed Tensor is erased once at the call and reaches the same kernels as a RuntimeTensor.

Python bindings#

Einsums’ Python surface is generated, not hand-written. Apiary, a libclang tool, walks the annotated C++ headers and emits pybind11 translation units plus .pyi stubs. The native extension ends up at ${BUILD}/lib/einsums/_core.cpython-*.so. Pure Python wrappers in libs/Einsums/Python/python/einsums/ add ergonomics on top.

The consequence of this is that, when a C++ symbol is added with the right annotation, the Python binding will be created automatically on the next build. No hand-written glue to forget to update. The bindings always track the C++ surface.

See the Python module documentation for the call surface and the codegen annotation reference.

Distributed computing#

The Comm module is the foundation for running Einsums across MPI ranks. The model is:

  • A ProcessGrid factors the world communicator into a 2D \(P_r \times P_c\) grid with row and column sub-communicators.

  • A DistributionDescriptor says, per tensor axis, whether the axis is replicated, split along the grid’s row dimension, or split along the column dimension.

  • ComputeGraph passes do the actual partitioning and communication scheduling:

    • DistributionPlanning assigns each einsum’s axes to grid axes (target indices on A go to Row, target indices on B to Col, shared link to None or balanced reduction).

    • Materialization resizes deferred tensors to per-rank slices.

    • InputSlicing creates rank-local views of pre-allocated inputs.

    • SUMMAExpansion rewrites einsums on square grids into the standard broadcast + GEMM loop.

    • CommunicationInsertion adds allreduce after distributed contractions when needed.

    • CommunicationScheduling splits blocking allreduce into async iallreduce + wait so communication overlaps compute.

For development and CI on machines without MPI, Comm falls back to a single-process mock backend that exposes the same API, so the passes above can be exercised without a real MPI installation.

GPU layer#

The GPU module is a thin abstraction over the device-side primitives, including memory allocation, streams, copies, and device-side BLAS. On Apple Silicon the MPS backend is built by default and runs single-precision GEMM and GEMV on the GPU, leaving double and complex types to Accelerate; the CUDA backend is in place with validation on real hardware pending. The production GPU path will land alongside the planned Ozaki mixed-precision tile-GEMM work. The same PackedGemm plan abstraction is intended to drive the GPU backend once the kernel side is implemented.

Build configuration#

A handful of CMake options gate the optional layers:

  • EINSUMS_BUILD_PYTHON builds the libtooling codegen, generates the pybind translation units, and emits _core.*.so.

  • EINSUMS_PYBIND_NUM_TU splits every module’s generated binding across that many translation units, overriding the per-module count a module declares with PYBIND_NUM_TU. Only ComputeGraph declares one, because only its binding is large enough for the memory saving to outweigh re-parsing the header set once per shard. Raise it on a build whose memory allowance is tighter than a developer machine’s; set it to 1 to turn sharding off.

  • EINSUMS_WITH_MPI replaces Comm’s mock backend with a real Open MPI or MPICH integration.

  • EINSUMS_WITH_CUDA enables the CUDA backend, which is pending validation work.

  • EINSUMS_WITH_MPS enables the Metal Performance Shaders backend; it is on by default on macOS.

  • EINSUMS_WITH_PROFILER enables the Profile instrumentation hooks.

  • EINSUMS_WITH_SANITIZERS=address,leak,undefined / EINSUMS_WITH_SANITIZERS=thread builds with the corresponding Clang/GCC sanitizers.

See the per-module documentation for the option each module reacts to.

Where to go from here#