Skip to main content
v2026.11,986 entries · CC-BY 4.0

NumPy Einsum Guide: Syntax, Paths & Tensor Math

Master NumPy einsum for multidimensional array contractions, optimize execution paths with einsum_path, and troubleshoot index errors in Python research.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

What it is used for in research

The numpy.einsum function evaluates the Einstein summation convention on multi-dimensional NumPy arrays (ndarray). It provides scientific researchers and data analysts with a unified, expressive interface to execute array operations—such as tensor contractions, matrix multiplication, batch dot products, inner and outer products, diagonal extractions, and multi-axis transpositions—using compact subscript notation.

In scientific computing workflows, multi-dimensional data structures frequently emerge across experimental domains. In cognitive neuroscience and electrophysiology, researchers handling multi-channel time-series data with packages like MNE-Python and structural data in diffusion tensor imaging compute trial-by-trial spatial covariance matrices and directional diffusion tensors across subjects, sensors, and temporal windows. In quantitative genomics and bioinformatics, high-dimensional arrays represent variant-by-individual interaction matrices across experimental cohorts.

Rather than chaining successive calls to np.transpose(), np.reshape(), np.matmul(), and np.sum()—which require allocating intermediate memory buffers—researchers use numpy.einsum to express the complete index transformation in a single operation. When integrated with multivariate dimensionality reduction workflows like principal component analysis in Python or linear discriminant analysis, subscript expressions make high-dimensional coordinate projections explicit, reproducible, and computationally efficient.

How to install or access it

NumPy is distributed officially through the Python Package Index (PyPI) and Conda package repositories. The numpy.einsum function is included directly in the core NumPy library without requiring separate add-on modules.

Modern NumPy releases (NumPy 2.x) require a 64-bit Python environment running Python 3.10 or higher. Install or upgrade NumPy using one of the following official package manager commands:

# Installation via PyPI
pip install numpy

# Installation via Conda Forge
conda install -c conda-forge numpy

Verify the installation and check the active library version in your scientific environment:

import numpy as np
print(np.__version__)

The official function signature from the NumPy API reference is:

numpy.einsum(subscripts, *operands, out=None, dtype=None, order='K', casting='safe', optimize=False)

The subscript string defines how array dimensions map to indices. NumPy supports two subscript modes:

  • Explicit mode: The subscript string contains the output delimiter arrow -> (for example, 'ij,jk->ik'). Input labels specify operand axes, and output labels explicitly dictate the retained axes and their exact dimensional order. Any index present in the inputs but omitted from the output is summed over. Explicit mode prevents ambiguity and is the recommended standard for research code.
  • Implicit mode: The subscript string omits the arrow (for example, 'ij,jk'). Labels appearing exactly once across all inputs are retained in alphabetical order in the output, while labels appearing two or more times are summed.
  • Ellipsis broadcasting (...): Placing an ellipsis in the subscript string (for example, '...ij,...jk->...ik') enables batch broadcasting across arbitrary leading dimensions without manual reshaping.

Step-by-step instructions

The following numbered procedure demonstrates how to compute multi-channel spatio-temporal covariance on research sensor arrays, optimize the contraction pathway, and execute the calculation using numpy.einsum.

  1. Construct the research data arrays and inspect shapes.
    Simulate a sensor dataset consisting of 100 trials, 32 spatial recording channels, and 256 time samples per trial. Confirm array rank and dimensions before drafting subscript strings:

    import numpy as np
    
    # Simulate research data: shape (trials, channels, time)
    rng = np.random.default_rng(seed=42)
    trials, channels, time_points = 100, 32, 256
    signals = rng.standard_normal((trials, channels, time_points))
    
    print("Input signal shape:", signals.shape)
    # Output: (100, 32, 256)
    
  2. Formulate the explicit subscript equation for covariance.
    To compute spatial covariance across channels, multiply each channel by every other channel across all trials and sum along the temporal axis (index t). Using explicit notation where b represents trial batch, i and j represent channel pairs, and t represents time:

    # Contract time axis 't' and sum across trials 'b' to produce channel covariance (i, j)
    subscripts = "bit,bjt->ij"
    
  3. Profile the contraction path using numpy.einsum_path.
    Before executing multi-tensor expressions, call numpy.einsum_path to inspect theoretical scaling, FLOP requirements, and peak intermediate memory allocation:

    path, path_info = np.einsum_path(subscripts, signals, signals, optimize='greedy')
    print(path_info)
    
  4. Execute the contraction with path optimization enabled.
    Pass optimize='greedy' (or optimize=True) into np.einsum to execute the contraction plan identified by the optimizer:

    cov_matrix = np.einsum(subscripts, signals, signals, optimize='greedy')
    
    # Normalize by degrees of freedom (trials * time_points - 1)
    cov_matrix /= (trials * time_points - 1)
    
    print("Resulting covariance matrix shape:", cov_matrix.shape)
    # Output: (32, 32)
    
  5. Broadcast across variable experimental dimensions using ellipses.
    If datasets contain variable hierarchical levels (such as participant cohorts, sessions, and blocks), use ellipsis notation (...) to maintain batch invariance without changing subscript logic:

    # Contract time 't' while preserving all leading experimental dimensions
    batch_cov = np.einsum("...it,...jt->...ij", signals, signals, optimize='greedy')
    print("Batch covariance shape:", batch_cov.shape)
    # Output: (100, 32, 32)
    

Output and how to read it

The primary output of numpy.einsum is an ndarray whose shape, memory layout, and precision depend on the input parameters and subscript configuration.

When reading and validating the output of an einsum operation in a research pipeline, evaluate three structural characteristics:

  • Output dimensional shape: In explicit mode (->), the shape of the returned array corresponds strictly to the characters specified to the right of the arrow. If the output string is empty (for example, 'i,i->' for a vector dot product), the function returns a 0-dimensional scalar array. In ellipsis operations ('...it,...jt->...ij'), leading dimensions are broadcast according to standard NumPy broadcasting rules.
  • Data type precision (dtype): By default, numpy.einsum infers the calculation and output data type from the input operands via safe type casting. If higher arithmetic precision is required to avoid numerical overflow in summation loops (such as accumulating float32 experimental measurements into float64 sums), explicitly set the parameter dtype=np.float64.
  • Contraction diagnostics from numpy.einsum_path: The string summary printed from einsum_path reports the complete contraction plan. Key diagnostic metrics include:
    • Complete contraction list: A sequence of tuple indices showing which pairs of tensors are combined at each step.
    • Scaling: The asymptotic polynomial complexity (such as 3 for an $O(N^3)$ matrix multiplication).
    • Optimized vs. naive FLOP count: The total number of floating-point multiplication and addition steps required. For multi-tensor chains, path optimization routinely reduces arithmetic work by several orders of magnitude.
    • Largest intermediate array: The maximum number of elements held in temporary memory during reduction, crucial for preventing out-of-memory errors on high-performance compute clusters.

Troubleshooting

When constructing complex tensor operations, incorrect subscript syntax or mismatched array dimensions will trigger specific runtime exceptions. The following table outlines verified causes and solutions for common numpy.einsum errors:

Error Message Root Cause Diagnostic & Remediation
ValueError: einstein sum subscripts string contains too many subscripts The subscript string contains more comma-separated input terms than the number of operand arrays supplied to the function. Count the comma-separated segments on the left side of -> and ensure they match len(operands) exactly.
ValueError: operand has more dimensions than subscripts given in einstein sum An operand array possesses higher rank (more dimensions) than the number of index characters assigned to it in the subscript string. Verify array dimensions with array.ndim. Add characters to cover each axis, or insert an ellipsis (...) to absorb leading dimensions.
ValueError: dimensions in operand 0 for collapsing index do not match A subscript label is repeated within a single operand (indicating a diagonal or trace operation), but the corresponding axes have different lengths. A diagonal extraction (such as 'ii->i') requires square dimensions. Confirm that array.shape[axis1] == array.shape[axis2] before extraction.
ValueError: output subscript 'x' does not appear in the input subscripts An index character was written to the right of -> that was not declared in any input operand to the left. Ensure all output indices exist in the input operands. einsum can only contract or reorder existing axes; it cannot invent new dimensions.
High memory consumption / slow execution in multi-operand chains Omitting optimize=True on expressions with 3 or more operands defaults to unoptimized left-to-right evaluation, creating large intermediate tensors. Pass optimize='greedy' or optimize=True into numpy.einsum, or profile the contraction using numpy.einsum_path.

Free alternatives

Researchers working across scientific computing environments have access to several free, open-source alternatives for tensor contractions and Einstein summation:

Tool / Package Ecosystem / Language Function / Syntax Hardware Acceleration Autodiff Support Path Optimization Primary License
NumPy einsum Python np.einsum() CPU (BLAS backend) No Built-in (greedy/optimal via opt_einsum) BSD 3-Clause
PyTorch einsum Python, C++ torch.einsum() CPU, CUDA GPU, MPS Yes (torch.autograd) Supported via opt_einsum Modified BSD
JAX einsum Python jax.numpy.einsum() CPU, GPU, TPU (XLA) Yes (jax.grad) Automatic XLA fusion and path optimization Apache 2.0
R einsum R einsum::einsum() CPU (C++ via Rcpp) No Direct C++ loop evaluation MIT License
Julia TensorOperations Julia @tensor / tensorcontract() CPU, CUDA GPU (via CUDA.jl) Yes (Zygote.jl, Enzyme.jl) Built-in compile-time contraction tree optimizer MIT License

FAQ

What is the difference between explicit and implicit mode in numpy.einsum?

In explicit mode, the subscript string includes the arrow delimiter -> (for example, 'ij,jk->ik'), explicitly defining which indices appear in the output and in what order. In implicit mode, the arrow is omitted (for example, 'ij,jk'), and NumPy automatically outputs indices that appear only once in alphabetical order while summing across repeated indices. Explicit mode is strongly recommended in scientific research to avoid unintended axis transpositions.

When should optimize=True be used in numpy.einsum?

The optimize=True parameter should always be used when contracting three or more operand arrays. For two operands (such as basic matrix multiplication), optimization is unnecessary because only one contraction step exists. For multi-tensor chains, enabling optimization searches for the lowest-cost contraction tree using heuristic ('greedy') or exhaustive ('optimal') algorithms, preventing massive intermediate array allocations and reducing runtime by orders of magnitude.

How does ellipsis (…) broadcasting work in einsum expressions?

An ellipsis (...) acts as a wildcard representing zero or more leading batch dimensions. For example, the expression '...ij,...jk->...ik' performs matrix multiplication on the final two axes of the input arrays while automatically broadcasting across any preceding batch, subject, or trial dimensions. This eliminates the need to manually reshape multi-dimensional research arrays.

Can numpy.einsum modify arrays in place?

Yes. By specifying an existing pre-allocated array in the out parameter (for example, np.einsum('ij,jk->ik', A, B, out=C)), NumPy writes the contracted values directly into the target memory buffer. This practice minimizes memory churn in iterative research loops, such as Monte Carlo simulations or numerical differential equation solvers.

How does numpy.einsum compare to the standard matrix multiplication operator (@)?

The Python @ operator (invoking np.matmul) is specialized for 2D matrix multiplication and standard batch matrix multiplication. It calls highly tuned BLAS library routines (such as GEMM) and is generally faster for standard two-matrix products. However, numpy.einsum is substantially more flexible for higher-rank tensor operations, multidimensional traces, and custom index contractions that would otherwise require multiple reshaping and transposition steps.

Sources

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about NumPy Einsum Guide: Syntax, Paths & Tensor Math

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →