Einsum spec grammar
ferric contracts two tensors under a spec string such as ij,jk->ik. The same parser serves the Rust einsum! macro, ferric_tensors::einsum_dyn and the Python function ferric.einsum.
The grammar is stricter than numpy.einsum. A spec that breaks a rule is an error; there is no fallback to another algorithm.
Every example below is a test in crates/ferric-tensors/tests/einsum_spec_examples.rs with a hand-computed expected value. A further test fails if a spec tested there is missing from this page. The parser is crates/ferric-einsum-spec/src/lib.rs.
Entry points
| Entry point | Spec checked | Scale | Scalar spec returns |
|---|---|---|---|
einsum!(spec, &a, &b) (Rust macro) | at compile time; the spec must be a string literal | optional fourth argument, default 1.0 | f64 |
einsum_dyn(spec, a, b, scale) (Rust) | at run time, as TensorError | scale: f64 | 0-dimensional ArrayD<f64> |
ferric.einsum(spec, *operands, scale=1.0, out=None, beta=0.0) (Python) | at run time, as ValueError | scale keyword | Python float (the out array when out is given) |
einsum_chain_dyn(spec, &[operands], scale) (Rust) | at run time, as TensorError | scale: f64 | 0-dimensional ArrayD<f64> |
einsum_dyn_into(spec, a, b, out, alpha, beta), einsum_chain_into(spec, &[operands], out, alpha, beta) (Rust) | at run time, as TensorError | alpha: f64 | writes out |
The macro takes Tensor or ArrayD<f64> operands. For Tensor operands a debug build also checks that contracted and batch axes carry the same Axis label. A shape mismatch inside a macro call panics; einsum_dyn returns an error instead.
Grammar
spec = left "," right "->" output
left, right, output = zero or more index characters
- Spaces are removed before parsing.
- An index is one
char, andiandIare different indices. The parser splits on the first->and on,, so those characters cannot be indices. - The spec must contain
->and exactly two comma-separated inputs. (Three or more inputs are a chain of binary contractions; see below.) - No index may repeat within one term, including the output. Traces and diagonals of one operand (
ii,...) are rejected. - Each operand has as many axes as its term has indices;
einsum_dynchecks this.
Index classes
Each index falls in one class by where it appears.
| Appears in | Class | Effect |
|---|---|---|
| both inputs, not the output | contracted | summed; the GEMM inner axis |
| both inputs and the output | batch | element-wise; one GEMM per batch slice |
| one input and the output | free | kept in the output |
| one input only | error | implicit single-operand sums are not supported |
An index in the output that is in neither input is also an error.
Output order
The output lists indices in three groups: batch indices, then free indices of the left operand, then free indices of the right operand. Order within a group is free and sets the output axis order. A group that appears out of sequence is an error.
Three or more operands
ferric.einsum and einsum_chain_dyn accept three or more operands. The spec is evaluated as a fixed left-to-right chain of binary contractions, ((A B) C) D, in the order written. There is no contraction-order search, so the result is a deterministic function of the spec.
Each step is a binary contraction under the rules above. An index shared by the running result and the next operand is summed at that step unless a later operand or the output still carries it; then it is a batch index of that step. An index held by only one side of a step must be carried by a later operand or the output, or the step is an implicit single-operand sum and the call is an error that names the step. The intermediate's axes are ordered batch, left-free, right-free, each in term order. The output must follow the group order for the last step, with the running result as the left side. scale multiplies the last step only.
Examples
Operands used below: A = [[1,2,3],[4,5,6]] (2x3), B = [[1,0],[0,1],[1,1]] (3x2).
| Spec | Operation | Result |
|---|---|---|
ij,jk->ik | matrix product A B | [[4,5],[10,11]] |
ij , jk -> ik | same; spaces ignored | [[4,5],[10,11]] |
ab,bc->ac | same; letters are labels only | [[4,5],[10,11]] |
ij,j->i | A times [1,1,1] | [6,15] |
i,j->ij | outer product of [1,2] and [3,4,5] | [[3,4,5],[6,8,10]] |
ij,ij-> | full contraction A:A | 91 |
ij,ij->ij | Hadamard product A*A | [[1,4,9],[16,25,36]] |
kij,kij->ij | dot over k per (i,j), k=2, shape (2,1,3) | [[17,29,45]] |
ijk,kl->jil | i,j free in operand order j,i; shape (1,2,2) with (2,1) | shape (2,1,1) |
Writing into a buffer: out and beta
out and beta follow the BLAS convention C = alpha * A.B + beta * C, with alpha the scale. The GEMM writes the result into out itself: nothing is allocated for the result and there is no second pass over it for the scale or the accumulation.
out = np.zeros((no, nv, no, nv))
for bi, bj in chunks:
ferric.einsum("Pia,Pjb->iajb", bi, bj, out=out, beta=1.0) # out += result
out must be a writable, C-contiguous float64 numpy.ndarray of exactly the result's shape (0-d for a scalar spec) that shares no memory with an operand; anything else is a ValueError, raised before out is touched. With beta=0 (the default) the old contents of out are never read, so an uninitialised or NaN buffer is fine; beta=1 accumulates; beta without out is a ValueError. The call returns out. For three or more operands the last step writes into out; the intermediates are still allocated.
With out, scale is applied inside the GEMM instead of as a pass over the finished product, so for scale != 1 the last bits can differ from the same call without out. For scale == 1, beta == 0 the two are bit-identical. ferric.tensor.contract(out=..., accumulate=True) uses this natively for its last step when out is C-contiguous, does not overlap an operand and needs no transposition.
Scale
The scale multiplies the whole result. With scale -0.5, ij,jk->ik gives [[-2,-2.5],[-5,-5.5]]. For a scalar spec, scale 2 gives 182.
let s: f64 = einsum!("ij,ij->", &a, &a, 2.0); // 182.0
let d = einsum_dyn("ij,ij->", a.view(), a.view(), 2.0).unwrap();
assert_eq!(s, d[IxDyn(&[])]);
Errors
Each message is asserted verbatim in malformed_specs_are_errors and operand_mismatches_are_errors_at_run_time. einsum! reports parse errors as compile errors with the same text.
| Spec | Error |
|---|---|
ij,jk | einsum spec must contain '->' |
ij->ij | einsum spec must have exactly two comma-separated inputs |
ij,jk,kl->il | einsum is binary: exactly two inputs |
ii,jk->jk | index 'i' is repeated in the left operand (traces / diagonals of one operand are not supported) |
ij,jk->kk | index 'k' is repeated in the output (traces / diagonals of one operand are not supported) |
ij,jk->k | index 'i' appears in an input but is neither contracted nor in the output (implicit single-operand sums are not supported) |
ij,jk->ikz | output index 'z' is not a free or batch index of either input |
ij,jk->ki | output indices must be listed as (batch indices, then left-operand free indices, then right-operand free indices) to match the runtime axis order |
einsum_dyn adds two checks that are TensorError::Operand (Python ValueError):
- an operand whose number of axes differs from its term;
- a shared index whose extents differ between the operands.
An operand with a zero-extent axis returns an array of zeros with the output shape.
Execution
The contraction is one binary product, not a loop over indices.
- Each operand is read as a (batch, free, contracted) 3-d view. The axes of each group are merged into one stride whenever they are a contiguous run of memory in the group's order, so the identity order, the swap of two groups, a batch axis that is not leading (
aPi) and every other contiguous-group layout are read in place; dgemm absorbs the transpose in itstransa/transbflag. Only genuinely interleaved orders (and non-positive strides) are gathered into a contiguous copy, in parallel for large operands. - The kernel depends on the shape:
- no contracted extent (
ij,ij->ij,ia,ib->iab,i,j->ij): an element-wise or per-slice outer product, no GEMM, parallel over output rows; - batch indices and no free extent (
ijab,ijab->ij,kij,kij->ij): a batched dot, parallel over the batch, k summed in 8 partial sums (this order is the kernel's own, not dgemm's, and is independent of the thread count); - one GEMM (no batch), via
ndarray::linalg::general_mat_mul.ferric-tensorsbuilds ndarray with itsblasfeature throughndarray-linalg, so the product is an OpenBLASdgemm. Large products split output rows over rayon bands; this path is bit-identical to the serial product; - batch indices with free extents (
Pia,Pib->Pab): one dgemm per batch slice, rayon over the batch when the slices are small (OpenBLAS pinned to one thread inside), over row bands inside each slice when they are large.
- no contracted extent (
- The contracted axis of a GEMM is summed in blocks of
GEMM_K_BLOCK(128), a coarse pairwise summation that is measurably more accurate than one full-k product. Measured on this engine, the block costs 5-10% of single-thread GEMM speed at k above 128 (each block re-reads and rewrites the result), not the large factor an unblocked comparison would suggest. scalemultiplies the finished product (a pass over the result), so every batch slice rounds exactly as the unbatched call would; without=it isalphainside the GEMM instead, andbetais the first block'sbeta.- The result is reshaped to the output shape.
Contractions run on the CPU unless the crate is built with the gpu feature.
Leave OPENBLAS_NUM_THREADS unset (one BLAS thread inside rayon regions), as described in Installation.