einsums.linalg#

Note

This page is generated by apiary from the binding annotations and the package’s Python source. Do not edit by hand.

Summary#

  • LuPivots — The row interchanges getrf produces, as something a graph can outlive.

  • abs — Graph-aware magnitude: out := |A|. Real or complex A produces real out. Dense or tiled.

  • axpby — Graph-aware AXPBY: Y = alpha * X + beta * Y (extended BLAS level-1).

  • axpy — Graph-aware AXPY: Y += alpha * X (BLAS level-1).

  • block_copy — Copy a contiguous N-dimensional sub-region of src into dst.

  • conj — Graph-aware in-place complex conjugate: A := conj(A). A no-op for real dtypes, matching numpy.conj on a real array. Captured as an opaque Custom node, since the einsum-rewriting passes do not reason about conjugation.

  • det — Determinant of a square matrix (returning scalar).

  • diagonal — Graph-aware diagonal extraction: out[i] := A[i, i].

  • direct_division

  • direct_product

  • dot — Python-friendly graph-aware dot: writes the result into result->data()[0].

  • dotc — Graph-aware Hermitian inner product: result := sum_i conj(A_i) * B_i.

  • element_transform — Python-friendly NAMED element_transform: the registry’s kernel, chosen by name.

  • gather — Copy an arbitrary index selection out of src into dst.

  • gemm — Graph-aware GEMM: C = alpha * op(A) * op(B) + beta * C.

  • gemv — Graph-aware GEMV: y = alpha * op(A) * z + beta * y.

  • ger — Graph-aware GER (rank-1 update): A += alpha * X * Y^T.

  • gerc — Graph-aware conjugating rank-1 update (GERC): A += alpha * X * Y^H.

  • gesv — Solve the linear system A * X = B in place.

  • getrf — LU-factorize A in place, recording the row interchanges in pivots.

  • getrs — Solve A * X = B in place against a factorization getrf produced.

  • grouped_axpby — One node holding many independent AXPBYs: Y_i = alphas[i] * X_i + betas[i] * Y_i for every entry.

  • grouped_direct_division — One node holding many independent element-wise quotients: C_i = alphas[i] * (A_i ⊘ B_i) + betas[i] * C_i for every member.

  • grouped_direct_product — One node holding many independent element-wise products: C_i = alphas[i] * (A_i ⊙ B_i) + betas[i] * C_i for every member.

  • grouped_dot — One node holding many independent dot products: results[i]->data()[0] = sum(A_i * B_i) for every entry.

  • grouped_gather_rotate — Emit one node holding many independent gather-and-rotate blocks: C_i[q, a, b] = sum_uv src[Q_i[q], U_i[u], U_i[v]] X_i[u, a] X_i[v, b], the whole run under one OpenMP region.

  • grouped_permute — One node holding many independent permutes: C_i = c_pfs[i] * C_i + a_pfs[i] * permute(A_i) for every member, all of them under one spec.

  • grouped_sandwich — Emit one node holding many independent dressed sandwich accumulations: C_i += sum_q B_q S_i B_q^T with B_q = A_i[q] - P_i^T M_i[q], the whole run under one OpenMP region.

  • heev — Hermitian eigendecomposition (in-place): A = V * diag(W) * V^H.

  • imag — Graph-aware imaginary part: out := Im(A). Complex A produces real out. For real A it is zeros, since Im(x) == 0, matching numpy .imag. Dense or tiled.

  • invert — In-place matrix inverse: A := A^-1.

  • max — Graph-aware maximum element (real dtypes), written into result->data()[0]. Backs the numpy-style A.max(). Real dtypes only, since complex ordering is not meaningful; use norm(MAXABS) for the largest magnitude.

  • norm — Python-friendly graph-aware norm: writes the result into result->data()[0].

  • outer_sum — Outer sum of N rank-1 vectors with per-axis coefficients.

  • pow — Matrix power: A^alpha via eigendecomposition.

  • qr — QR decomposition (returning): A = Q * R.

  • real — Graph-aware real part: out := Re(A). Complex A produces real out. For real A it is a copy, since Re(x) == x, matching numpy .real. Dense or tiled.

  • reshape — Graph-aware reshape: copy A into out, which has the same number of elements in a different shape.

  • scale — Graph-aware scale: multiplies A in place by the scalar factor.

  • scatter — Write src into an arbitrary index selection of dst.

  • scatter_add — Graph-aware accumulating scatter: dst[indices...] += src[...].

  • shift — Graph-aware in-place scalar shift: A += beta.

  • sqrt — Graph-aware element-wise square root: out := sqrt(A).

  • sum — Graph-aware sum of every element, written into result->data()[0].

  • sum_axes — Graph-aware reduction: sum A over axes, writing the surviving axes to out in their original order.

  • svd — Singular value decomposition (returning): A = U * diag(S) * Vt.

  • svd_dd — Divide-and-conquer singular value decomposition (returning): A = U * diag(S) * Vt.

  • syev — Real symmetric eigendecomposition (in-place): A = V * diag(W) * V^T.

  • syev_eig — Real symmetric eigendecomposition (returning): (V, W) = syev_eig(A).

  • symm_gemm — Graph-aware C = op(B)^T op(A) op(B), or op(B)^H op(A) op(B) with conjugate. A, B and C may be compile-time-rank matrices or runtime-rank tensors, as in gemm.

  • trace — Trace of a square matrix: sum(A_ii). Returns the scalar.

  • truncated_svd — Rank-k truncated SVD (returning): keeps the top k singular triples of A. Returns (U_k, S_k, Vt_k) with U_k of shape (m, k), S_k of shape (k,), and Vt_k of shape (k, n).

  • truncated_syev — Rank-k truncated symmetric eigendecomposition (returning): keeps the top k eigenpairs of a real symmetric A. Returns (eigenvectors, eigenvalues) where eigenvectors has shape (n, k) and eigenvalues has shape (k,).

  • Norm — Indicates the type of norm to compute.

  • Transpose — Transpose mode for a matrix operand, mapping 1:1 onto the BLAS op flag. Enumerators are the BLAS letters. None is avoided because it is a Python keyword.

  • Vectors — Compute modes for the singular value decomposition.

Classes#

class einsums.linalg.LuPivots#

The row interchanges getrf produces, as something a graph can outlive.

A pivot array is a list of BLAS integers, which is not one of the dtypes a tensor operand may carry, so it cannot be a graph TENSOR and cannot be a slot. It is instead a handle whose buffer is shared: getrf and getrs both bake a copy of the shared_ptr into their executors at capture time, so the buffer survives however long the graph does even if the handle the caller held is dropped first, and both see the same array on every replay.

Because the pivots ride outside the dataflow, they carry no ordering of their own. What orders a factorization against its solves is the FACTORIZATION TENSOR: getrf writes it, getrs reads it, and the hazard scan serializes the pair on that edge. A getrs against a handle whose matching getrf writes a different tensor has nothing holding the two together and is a bug in the caller.

The buffer is sized by getrf on the first execution and reused afterwards.

__init__() → None#

An empty pivot array. getrf sizes it to the order of the matrix it factors.

size: int#

The number of interchanges recorded, which is zero until a getrf node has executed.

(read-only)

Functions#

einsums.linalg.abs(out: Any, A: Any) → None#

Graph-aware magnitude: out := |A|. Real or complex A produces real out. Dense or tiled.

einsums.linalg.axpby(alpha: Any, X: Any, beta: Any, Y: Any) → None#

Graph-aware AXPBY: Y = alpha * X + beta * Y (extended BLAS level-1).

Like axpy but also scales the destination by beta first. X and Y must have the same dtype and shape.

einsums.linalg.axpy(alpha: Any, X: Any, Y: Any) → None#

Graph-aware AXPY: Y += alpha * X (BLAS level-1).

X and Y must have the same dtype and shape; the operation is element-wise. Eager outside graph capture; recorded as a node when inside a capture context.

einsums.linalg.block_copy(dst: Any, src: Any, dst_offsets: list[int], src_offsets: list[int], extents: list[int]) → None#

Copy a contiguous N-dimensional sub-region of src into dst.

For each axis k, copies extents[k] elements starting at src_offsets[k] in src into dst_offsets[k] in dst:

dst[dst_offsets + i] = src[src_offsets + i] for all i in extents

Both tensors must have the same rank and dtype. Uses per-axis strides so arbitrary memory layouts are handled correctly. Capture-aware: outside capture, runs immediately; inside capture, records a node with src as an input dependency and dst as an output.

Common patterns:

  • Extract occupied MO block: block_copy(&C_occ, C, {0,0}, {0,0}, {nbf, nocc})

  • Extract (ia|jb) ERI block: block_copy(&iajb, eri_mo, {0,0,0,0}, {0, nocc, 0, nocc}, {nocc, nvirt, nocc, nvirt})

einsums.linalg.conj(A: Any) → None#

Graph-aware in-place complex conjugate: A := conj(A). A no-op for real dtypes, matching numpy.conj on a real array. Captured as an opaque Custom node, since the einsum-rewriting passes do not reason about conjugation.

einsums.linalg.det(A: Any) → Any#

Determinant of a square matrix (returning scalar).

Cannot be used during graph capture (returns by value, so there is no destination slot). For complex inputs the determinant is itself complex.

einsums.linalg.diagonal(out: Any, A: Any) → None#

Graph-aware diagonal extraction: out[i] := A[i, i].

out is rank-1 with extent min(A.dim(0), A.dim(1)), matching numpy’s np.diag on a matrix. A rectangular A is fine; the shorter axis wins.

einsums.linalg.direct_division(alpha: Any, A: Any, B: Any, beta: Any, C: Any) → None#
einsums.linalg.direct_product(alpha: Any, A: Any, B: Any, beta: Any, C: Any) → None#
einsums.linalg.dot(A: Any, B: Any) → Any#
einsums.linalg.dot(result: Any, A: Any, B: Any) → None

Python-friendly graph-aware dot: writes the result into result->data()[0].

result is a pre-allocated rank-1 (or higher, but only element 0 is touched) tensor that gives Python users a graph-native scalar handle, so SCF energy patterns like e = ½ Σ D · (H+F) can be captured.

einsums.linalg.dotc(result: Any, A: Any, B: Any) → None#

Graph-aware Hermitian inner product: result := sum_i conj(A_i) * B_i.

The conjugating counterpart of dot, the bilinear sum A_i B_i. For real dtypes this coincides with dot. Backed by true_dot, which uses BLAS dotc on the contiguous complex path.

einsums.linalg.element_transform(C: Any, op_name: str) → None#
einsums.linalg.element_transform(C: Any, unary_op: Callable[[Any], Any]) → None

Python-friendly NAMED element_transform: the registry’s kernel, chosen by name.

The same operation the string_view overload above records, reachable from Python. Worth having as more than a convenience: a node built from a registered name says WHAT it computes, where a node holding a Python callable says only that something is applied to every element. A pass that has to recognize a reciprocal can read the first and not the second, and LaplaceTransform is one, so a caller who wants their denominator recognized needs this spelling rather than a lambda.

Parameterized ops are not reachable here yet; nothing in the Python surface needs one, and adding the policy number is a second overload rather than a default argument.

Parameters:
  • C – The tensor to transform in place.

  • op_name – Name of the kernel in the process’s element-op registry.

einsums.linalg.gather(dst: Any, src: Any, indices: list[list[int]], axes: list[int] = std::vector<size_t>{}) → None#

Copy an arbitrary index selection out of src into dst.

For each axis k, indices[k] lists the positions of src to take along that axis:

dst[i0, i1, …] = src[indices[0][i0], indices[1][i1], …]

This is the outer-product selection numpy spells A[np.ix_(rows, cols)], not the zipped selection A[rows, cols].

Every axis needs an explicit list; there is deliberately no “whole axis” wildcard. Spelling it as the empty list would be the natural choice and is the wrong one: the callers are domain-restricted methods, an empty domain is a legitimate (if degenerate) input there, and having it silently expand to the entire axis would turn a screened-out domain into a full-rank one with no error. An empty list therefore selects nothing, and a whole axis is std::iota / range(n) at the call site.

block_copy covers the contiguous case; this covers the case where the wanted elements are scattered, which is what domain-restricted methods do constantly: a local-correlation pair domain is a sorted list of orbital indices, and every operand is A[domain, domain]. Doing that on the host forces the extraction out of the graph, which is what this exists to avoid.

Both tensors must have the same rank and dtype, and dst’s extent on each axis must equal the number of indices selected there. Capture-aware: outside capture it runs immediately; inside, it records a node with src as an input and dst as an output, so a whole per-pair setup can be one graph.

axes optionally reorders the axes on the way out: source axis k lands on destination axis axes[k], so

dst[…, i_{axes[k]} = ik, …] = src[…, indices[k][ik], …]

Empty (the default) is the identity. This exists because the alternative is a gather followed by a permute, and both are full passes over the result: selecting and reordering together is one pass, and the traversal already walks the destination through per-axis strides, so permuting is only a different set of strides. Callers that need to reinterpret rather than move axes want RuntimeTensor::reshape_view, which does not copy at all.

einsums.linalg.gemm(alpha: Any, A: Any, B: Any, beta: Any, C: Any) → None#
einsums.linalg.gemm(alpha: Any, A: Any, B: Any, beta: Any, C: Any, trans_a: Transpose = einsums::linear_algebra::Transpose::N, trans_b: Transpose = einsums::linear_algebra::Transpose::N) → None

Graph-aware GEMM: C = alpha * op(A) * op(B) + beta * C.

trans_a and trans_b (Python kwargs, default False) request the transpose of the corresponding matrix. All three tensors must be rank 2; a clear RankError is raised up front otherwise rather than letting the BLAS kernel fail mid-pipeline.

A, B, C may be any combination of owning tensor and view, and of the compile-time-rank (Tensor) and runtime-rank (RuntimeTensor) families, so long as they share an underlying element type. Views alias their parents so writes through C-view land in the parent and the optimization passes see the dependency via TensorHandle::aliases.

einsums.linalg.gemv(alpha: Any, A: Any, z: Any, beta: Any, y: Any) → None#
einsums.linalg.gemv(alpha: Any, A: Any, z: Any, beta: Any, y: Any, trans_a: Transpose = einsums::linear_algebra::Transpose::N) → None

Graph-aware GEMV: y = alpha * op(A) * z + beta * y.

trans_a (Python kwarg, default False) transposes A. A must be rank 2 and z, y must be rank 1; a RankError is raised otherwise.

einsums.linalg.ger(alpha: Any, X: Any, Y: Any, A: Any) → None#

Graph-aware GER (rank-1 update): A += alpha * X * Y^T.

Outer product of vectors X and Y added to matrix A. X and Y must be rank 1; A must be rank 2.

einsums.linalg.gerc(alpha: Any, X: Any, Y: Any, A: Any) → None#

Graph-aware conjugating rank-1 update (GERC): A += alpha * X * Y^H.

The Hermitian counterpart of ger, which computes A += alpha * X * Y^T: here the second vector is conjugated. Complex operands only; for real operands use ger. Backed by linear_algebra::gerc (BLAS cgerc/zgerc).

einsums.linalg.gesv(A: Any, B: Any) → int#

Solve the linear system A * X = B in place.

On return B holds X and A holds its LU factorization. B may be rank 1 (single right-hand side) or rank 2 (multiple right-hand-side columns). Returns the LAPACK info code: 0 on success, positive i if A is singular at row i.

einsums.linalg.getrf(A: Any, pivots: LuPivots) → int#

LU-factorize A in place, recording the row interchanges in pivots.

On return A holds L and U in the LAPACK packing (the unit diagonal of L is not stored) and pivots holds the interchanges, sized to the order of A. Unlike gesv, the factorization survives every solve made against it, so one getrf feeds any number of getrs calls. Returns the LAPACK info code: 0 on success, positive i if U(i,i) is exactly zero - the factorization is still complete, but a solve against it is meaningless.

The same pivots object must be handed to the matching getrs, and ordering rides on A rather than on the pivots.

einsums.linalg.getrs(A: Any, pivots: LuPivots, B: Any) → int#

Solve A * X = B in place against a factorization getrf produced.

A is the LU factorization and pivots the interchanges the matching getrf left; both are READ, so the pair serves any number of right-hand sides and any number of replays. B may be rank 1 (a single right-hand side) or rank 2 (one per column), and on return holds X. Returns the LAPACK info code, which is 0 unless an argument was invalid.

einsums.linalg.grouped_axpby(alphas: list[float], x_list: list[Any], betas: list[float], y_list: list[Any]) → None#

One node holding many independent AXPBYs: Y_i = alphas[i] * X_i + betas[i] * Y_i for every entry.

The grouped counterpart of axpby, and the accumulating half of the pattern grouped_dot reduces into: a local-correlation residual computes a scalar per pair or per neighbour and then adds it, scaled, into one element of a shared matrix; this makes that one node.

Entries run SEQUENTIALLY inside the node, in the order they were passed. That is load-bearing twice over. It makes each entry the same bits the single call would have written, and it makes REPEATED DESTINATIONS legal: a family whose entries all accumulate into one element - a sum over a pair’s neighbours, say

  • keeps its term order, because the entries are applied in the order the caller wrote them and no two run at once. So unlike grouped_batched_gemm, which rejects a shared destination because its members may run concurrently, this operation accepts one and defines it.

The prefactors are per entry, which is the difference from axpby that makes merging worthwhile: the accumulations a residual wants to merge disagree on their coefficients.

Outside capture this executes immediately, so the same call works eagerly.

Parameters:
  • alphas – Per-entry prefactor on X_i.

  • x_list – Sources, same length as alphas.

  • betas – Per-entry prefactor on Y_i. A non-zero entry means that Y_i is read as well as written, which the node records as a dependency.

  • y_list – Destinations, same length as alphas. May repeat.

einsums.linalg.grouped_direct_division(alphas: list[Any], a_list: list[Any], b_list: list[Any], betas: list[Any], c_list: list[Any]) → None#

One node holding many independent element-wise quotients: C_i = alphas[i] * (A_i ⊘ B_i) + betas[i] * C_i for every member.

The grouped counterpart of direct_division, and the shape an amplitude update reaches it in: one residual divided by its own denominator block per entity. Everything grouped_direct_product says about concurrency, bit-identity and distinct destinations holds here unchanged.

Outside capture this executes immediately, so the same call works eagerly.

einsums.linalg.grouped_direct_product(alphas: list[Any], a_list: list[Any], b_list: list[Any], betas: list[Any], c_list: list[Any]) → None#

One node holding many independent element-wise products: C_i = alphas[i] * (A_i ⊙ B_i) + betas[i] * C_i for every member.

The grouped counterpart of direct_product, and the shape a local-correlation residual reaches it in: one Hadamard product per entity against that entity’s own denominator or weight block, hundreds of them.

Members run CONCURRENTLY, which an element-wise kernel can afford: no member’s result depends on how the run was divided, so every member writes the bits the single call would have written whatever the schedule. Each member calls the same linear_algebra::direct_product a single direct_product node calls, so the grouped form adds a loop and nothing else. Destinations must be distinct.

Outside capture this executes immediately, so the same call works eagerly.

einsums.linalg.grouped_dot(results: list[Any], a_list: list[Any], b_list: list[Any]) → None#

One node holding many independent dot products: results[i]->data()[0] = sum(A_i * B_i) for every entry.

The entries run SEQUENTIALLY inside the node, in the order they were passed, each through the same linear_algebra::dot a single dot_python call makes. That is the point of the operation and not an implementation detail: this exists for workloads whose gate is bit-identity, so the result has to be the same bits as the loop of single calls it replaces, entry by entry. A parallel-within-node form would reduce in a different order on nothing but its own schedule, and it would have nothing to gain - a dot into a scalar has no arithmetic to spread. What is saved is the per-node dispatch, which at the block sizes local-correlation methods produce is the whole cost: a DLPNO-CCSD iteration reached ~1,700 of these, one node each.

Each entry’s own reduction runs at VENDOR WIDTH ONE, under blas::SerialVendorScope, and that is part of the contract rather than a tuning choice. A threaded dot sums per-thread partials, so its last bits are a function of how many threads the caller happened to present - and this node is reached at whatever width its context has: eagerly from the main thread, from an executor worker, from inside a node-scoped width. Pinning the width makes every entry a function of its operands alone, so the same inputs give the same bits whatever is running around them. The entries may be dispatched from anywhere; it is each entry’s INTERNAL reduction that is fixed, and the entries themselves are already ordered by the caller’s list.

Because the entries are sequential, repeating a destination is well defined and means what the loop means - the last entry writing it wins. Unlike grouped_batched_gemm there is therefore nothing to reject.

Outside capture this executes immediately, so the same call works eagerly.

Parameters:
  • results – One length-1-or-larger destination per entry; only element 0 is written, matching the single form.

  • a_list,b_list – The operands, same length as results. Each entry’s A and B must agree on rank and shape, as dot requires; the entries need not agree with each other.

einsums.linalg.grouped_gather_rotate(c_list: list[Any], src: Any, q_list: list[list[int]], u_list: list[list[int]], x_list: list[Any]) → None#

Emit one node holding many independent gather-and-rotate blocks: C_i[q, a, b] = sum_uv src[Q_i[q], U_i[u], U_i[v]] X_i[u, a] X_i[v, b], the whole run under one OpenMP region.

The shape this exists for is the DLPNO-(T0) three-external block, which the naive emission spells as a gather of the whole (Q|u v) domain block followed by two contractions - the gathered block and a half-transformed one of the same leading extent, both of them the largest tensors the phase ever holds, streamed four times over where one pass suffices. Here every member streams its selection of src once and keeps the rotation in cache, the auxiliary axis tiled into cache-resident blocks.

One source for the whole run, because that is what makes the streaming claim true: the members are domain-restricted selections of ONE parent, and giving each its own would only let a caller take the traffic back.

Both source axes are selected by the same index list and rotated by the same transform. The operation is the symmetric two-sided rotation X^T (Q|u v) X, which is the only form the callers have; an asymmetric one would need a second list and a second transform and is not this operation.

Every member is independent - destinations are distinct and each is ASSIGNED by one thread - so replays are deterministic whatever the schedule, and the result does not depend on the tiling at all (the tiled axis indexes no sum). Agreement with the gather-plus-two-contractions form it replaces is to roundoff rather than bitwise, because the two block their reductions differently.

Operand shapes per member, all column-major: src is (NQ, NU, NU) with the auxiliary axis fastest, X_i is (nu_i, nt_i) and column-contiguous, and C_i is (nq_i, nt_i, nt_i) where nq_i and nu_i are the lengths of the member’s index lists. A member with any extent zero is a quick return, except that an empty u selection writes its destination’s zeros.

Outside capture this executes immediately, so the same call works eagerly.

einsums.linalg.grouped_permute(spec: str, c_list: list[Any], a_list: list[Any], c_pfs: list[float], a_pfs: list[float]) → None#

One node holding many independent permutes: C_i = c_pfs[i] * C_i + a_pfs[i] * permute(A_i) for every member, all of them under one spec.

The grouped counterpart of string_permute, for the shape a local-correlation phase produces: one small reorder per pair or per triplet, hundreds of them, every one a node of its own. The arithmetic is unchanged and the dispatch is paid once.

Members run CONCURRENTLY and that costs nothing in reproducibility. A permute is element-wise - every output element is one input element scaled and added to what was there - so no member’s result depends on how the run was divided, and each member writes only its own destination. The last bit of every member is therefore the last bit the single call would have written, whatever the schedule. That is why this one threads where grouped_dot and grouped_axpby do not: theirs is a REDUCTION whose order a schedule would decide.

One spec for the whole run, because a batch drawn at one emission site has one. Per-member prefactors, because that is the difference between members worth merging: a term-by-term accumulation disagrees on its coefficients and on whether it is the first term (c_pf zero) or a later one.

Destinations must be distinct, for the concurrency above.

Outside capture this executes immediately, so the same call works eagerly.

Parameters:
  • spec – The permutation, e.g. "abc <- acb", shared by every member.

  • c_list – Destinations, one per member. Must be distinct.

  • a_list – Sources, same length as c_list.

  • c_pfs – Per-member prefactor on the destination. A non-zero entry means the member reads C as well as writing it, which the node records as a dependency.

  • a_pfs – Per-member prefactor on the source.

einsums.linalg.grouped_sandwich(c_list: list[Any], a_list: list[Any], m_list: list[Any], p_list: list[Any], s_list: list[Any]) → None#

Emit one node holding many independent dressed sandwich accumulations: C_i += sum_q B_q S_i B_q^T with B_q = A_i[q] - P_i^T M_i[q], the whole run under one OpenMP region.

The shape this exists for is the DLPNO-CCSD Eq. 76 residual term with its Eq. 93 T1-dressing, which the naive emission spells as a copy of A_i, an in-place dressing, a half product W the size of A_i, and a second contraction reading both - EIGHT full streams of the largest per-pair data in the iteration where one suffices. Here every member streams A_i once and keeps everything else in cache. The q slices are tiled into cache-resident blocks and accumulated in ascending order on one thread, so results match the naive emission to roundoff, not bitwise.

Every member is independent and members are threaded over, each one’s arithmetic serial inside its thread, so replays are deterministic whatever the schedule.

Operand shapes per member, all column-major: A_i is (nq, na, na) with the auxiliary axis fastest, M_i is (nq, nk, na), P_i is (nk, na), S_i is (na, na), and C_i is (na, na), accumulated into (beta = 1 semantics, so the node reads its destinations). P_i, S_i and C_i must be column-contiguous; A_i and M_i may be arbitrary views. Destinations must be distinct.

Outside capture this executes immediately, so the same call works eagerly.

einsums.linalg.heev(A: Any, W: Any) → None#

Hermitian eigendecomposition (in-place): A = V * diag(W) * V^H.

Complex analogue of syev. On return A holds eigenvectors as columns (when compute_eigenvectors=True); W holds the eigenvalues in ascending order. W is real even though A is complex.

einsums.linalg.imag(out: Any, A: Any) → None#

Graph-aware imaginary part: out := Im(A). Complex A produces real out. For real A it is zeros, since Im(x) == 0, matching numpy .imag. Dense or tiled.

einsums.linalg.invert(A: Any) → None#

In-place matrix inverse: A := A^-1.

A must be rank 2 and square. Internally calls getrf followed by getri; raises RankError if the input rank is wrong and the LAPACK kernel raises if A is singular.

einsums.linalg.max(result: Any, A: Any) → None#

Graph-aware maximum element (real dtypes), written into result->data()[0]. Backs the numpy-style A.max(). Real dtypes only, since complex ordering is not meaningful; use norm(MAXABS) for the largest magnitude.

einsums.linalg.norm(norm_type: Norm, A: Any) → Any#
einsums.linalg.norm(result: Any, norm_type: Norm, A: Any) → None

Python-friendly graph-aware norm: writes the result into result->data()[0].

For complex inputs the result is real-valued (e.g. complex<double> input requires a double result tensor). Use Norm::ONE, Norm::TWO, Norm::INFINITY_, Norm::FROBENIUS, etc.

einsums.linalg.outer_sum(result: Any, vectors: list[Any], coefficients: list[float]) → None#

Outer sum of N rank-1 vectors with per-axis coefficients.

Fills result with

result(i_0, i_1, ..., i_{N-1}) = Σ_k coefficients[k] * vectors[k](i_k)

Canonical use case is the MP2/CC energy denominator:

Δ(i,j,a,b) = ε_i + ε_j − ε_a − ε_b
  ↪ outer_sum(&Δ, {ε_occ, ε_occ, ε_virt, ε_virt}, {+1, +1, -1, -1})

If coefficients is empty, defaults to all +1.

Capture-aware: outside capture executes immediately; inside capture records a Custom node with each input vector and the result as dependencies. result->rank() must equal vectors.size() and result->dim(k) must equal vectors[k]->dim(0).

einsums.linalg.pow(A: Any, alpha: Any, cutoff: Any = std::numeric_limits<typename AType::ValueType>::epsilon()) → GeneralRuntimeTensor#

Matrix power: A^alpha via eigendecomposition.

Returns a freshly-allocated square matrix. alpha may be negative; an optional cutoff zeros out eigenvalues whose magnitude is below cutoff * max|eig| before exponentiation (guards against near-singular inputs when alpha < 0). Cannot be used during graph capture (returns by value); A is left unmodified.

einsums.linalg.qr(A: Any) → tuple[GeneralRuntimeTensor, GeneralRuntimeTensor]#

QR decomposition (returning): A = Q * R.

Returns the tuple (Q, R) where Q is orthogonal (or unitary for complex inputs) and R is upper-triangular. Cannot be used during graph capture; A is left unmodified.

einsums.linalg.real(out: Any, A: Any) → None#

Graph-aware real part: out := Re(A). Complex A produces real out. For real A it is a copy, since Re(x) == x, matching numpy .real. Dense or tiled.

einsums.linalg.reshape(out: Any, A: Any, row_major: bool) → None#

Graph-aware reshape: copy A into out, which has the same number of elements in a different shape.

row_major picks which linear order the elements are walked in, and it is NOT a formality. Einsums tensors are column major, so the natural order here is column major (row_major = false); numpy’s reshape defaults to row major, and code ported from it means the other one. Getting it wrong silently transposes blocks rather than failing, so the argument is required and has no default.

This copies. It is not a view: a reshape that could alias would have to reason about strides, and the callers here are assembling operands for BLAS which wants a fresh contiguous buffer anyway.

einsums.linalg.scale(factor: Any, A: Any) → None#

Graph-aware scale: multiplies A in place by the scalar factor.

einsums.linalg.scatter(dst: Any, src: Any, indices: list[list[int]]) → None#

Write src into an arbitrary index selection of dst.

The inverse of gather, with the index lists naming positions in the DESTINATION rather than the source:

dst[indices[0][i0], indices[1][i1], …] = src[i0, i1, …]

which is numpy’s A[np.ix_(rows, cols)] = B. Elements of dst outside the selection are left alone, so this is a placement, not an assignment of the whole tensor. That is what a domain-restricted result needs: a pair’s block is computed in its own small domain basis and then dropped into its slot in the full-length container.

As with gather, an empty index list selects nothing rather than acting as a whole-axis wildcard, and a whole axis is an explicit range at the call site.

Repeated indices are rejected. In a gather a repeat is harmless - the same element is read twice - but in a scatter it means two writes to one destination element, and which one survives depends on iteration order. The callers here build index lists from orbital domains, where a repeat is a bug rather than an intent, so it is diagnosed instead of silently resolved. An accumulating scatter would be a different operation, and is not this one.

einsums.linalg.scatter_add(dst: Any, src: Any, indices: list[list[int]]) → None#

Graph-aware accumulating scatter: dst[indices...] += src[...].

numpy’s np.add.at. The companion to scatter rather than a relaxation of it: scatter REJECTS repeated indices, because a plain write twice to one element leaves the result depending on loop order. Under an accumulation that ambiguity disappears - addition is commutative - so repeats are meaningful here and are allowed.

einsums.linalg.shift(beta: Any, A: Any) → None#

Graph-aware in-place scalar shift: A += beta.

The additive complement of scale. Unlike the Python-callable element_transform_python (a Python call per element), this is a tight compiled loop, so it’s the fast backing for the numpy-style scalar + / - operators (e.g. A + 1.0, A += c). It works in place with no allocation, which is what lets a denominator scratch be reused across a loop instead of allocating a fresh tensor per iteration. Records an opaque @ref OpKind::Custom node when capturing (no einsum pass rewrites it), or runs eagerly otherwise.

Walks the contiguous backing storage (data()[0..size())), matching element_transform_python’s convention. This is correct for dense tensors and the contiguous views the operators produce.

einsums.linalg.sqrt(out: Any, A: Any) → None#

Graph-aware element-wise square root: out := sqrt(A).

Distinct from pow, which is a MATRIX power computed by eigendecomposition (that is what its cutoff argument discards) and is a returning form that rejects capture. This is the element-wise partner to abs, and the two together are what a numerical sqrt(abs(X)) needs without dropping to the host between them.

Real dtypes only: the square root of a negative real is where a caller wants to decide, not have the library pick a branch. Negative inputs throw.

einsums.linalg.sum(result: Any, A: Any) → None#

Graph-aware sum of every element, written into result->data()[0].

Mirrors dot_python’s scalar-into-[1]-tensor convention: eager when not capturing, an opaque OpKind::Custom node otherwise. Stride-correct (works on slice/transpose views). Backs the numpy-style A.sum() / A.mean().

einsums.linalg.sum_axes(out: Any, A: Any, axes: list[int]) → None#

Graph-aware reduction: sum A over axes, writing the surviving axes to out in their original order.

sum already reduces a whole tensor to a scalar; this is the axis-wise form, numpy’s A.sum(axis=...). out must have rank rank(A) - axes.size() with the extents of the axes not being summed. out is zeroed first, so this assigns rather than accumulates.

einsums.linalg.svd(A: Any) → tuple[GeneralRuntimeTensor, GeneralRuntimeTensor, GeneralRuntimeTensor]#

Singular value decomposition (returning): A = U * diag(S) * Vt.

Returns the tuple (U, S, Vt). S is real even for complex inputs. U and Vt are always present, and the user can post- filter for the “no vectors” case if needed. Cannot be used during graph capture (returns by value); A is left unmodified.

einsums.linalg.svd_dd(A: Any, job: Vectors = einsums::linear_algebra::Vectors::ALL) → tuple[GeneralRuntimeTensor, GeneralRuntimeTensor, GeneralRuntimeTensor]#

Divide-and-conquer singular value decomposition (returning): A = U * diag(S) * Vt.

Faster than svd for large matrices; uses LAPACK’s gesdd driver. Returns (U, S, Vt) like svd. job controls whether the singular vectors are computed (ALL, SOME, or NONE). Cannot be used during graph capture (returns by value); A is left unmodified.

einsums.linalg.syev(A: Any, W: Any) → None#

Real symmetric eigendecomposition (in-place): A = V * diag(W) * V^T.

On return, when compute_eigenvectors=True (the default), A holds the eigenvectors as columns; W holds the eigenvalues in ascending order. A must be rank 2 and square; W must be rank 1 with size A.dim(0). For the returning form (allocates fresh outputs) see syev_eig.

einsums.linalg.syev_eig(A: Any) → tuple[GeneralRuntimeTensor, GeneralRuntimeTensor]#

Real symmetric eigendecomposition (returning): (V, W) = syev_eig(A).

Allocates fresh tensors for the eigenvectors and eigenvalues and returns them as a tuple. Cannot be used during graph capture; for the in-graph form use the in-place cg::syev(A, W) with pre-allocated outputs. A is left unmodified.

einsums.linalg.symm_gemm(A: Any, B: Any, C: Any, conjugate: bool = False) → None#

Graph-aware C = op(B)^T op(A) op(B), or op(B)^H op(A) op(B) with conjugate. A, B and C may be compile-time-rank matrices or runtime-rank tensors, as in gemm.

einsums.linalg.trace(A: Any) → Any#
einsums.linalg.trace(result: Any, A: Any) → None

Trace of a square matrix: sum(A_ii). Returns the scalar.

Cannot be used during graph capture (returns by value, so there is no destination slot). For the in-graph form use the four-argument cg::trace(&result, A) with a pre-allocated scalar.

einsums.linalg.truncated_svd(A: Any, k: int) → tuple[GeneralRuntimeTensor, GeneralRuntimeTensor, GeneralRuntimeTensor]#

Rank-k truncated SVD (returning): keeps the top k singular triples of A. Returns (U_k, S_k, Vt_k) with U_k of shape (m, k), S_k of shape (k,), and Vt_k of shape (k, n).

Randomized algorithm with over-sampling factor 5, which requires A.dim(0) >= k + 5. Smaller inputs raise IndexError from the projection step. Results are approximate; expect small drift versus a full svd.

Cannot be used during graph capture (returns by value); A is left unmodified.

einsums.linalg.truncated_syev(A: Any, k: int) → tuple[GeneralRuntimeTensor, GeneralRuntimeTensor]#

Rank-k truncated symmetric eigendecomposition (returning): keeps the top k eigenpairs of a real symmetric A. Returns (eigenvectors, eigenvalues) where eigenvectors has shape (n, k) and eigenvalues has shape (k,).

Randomized algorithm with over-sampling factor 5, which requires A.dim(0) >= k + 5. Smaller inputs raise IndexError from the projection step. Results are approximate top-k eigenpairs; expect small drift versus a full syev, especially for tightly clustered eigenvalues.

Cannot be used during graph capture (returns by value); A is left unmodified.

Enumerations#

class einsums.linalg.Norm#

Indicates the type of norm to compute.

MAXABS = 77#

\(val = max(abs(Aij))\), largest absolute value of the matrix A.

ONE = 49#

\(val = norm1(A)\), 1-norm of the matrix A (maximum column sum)

INFTY = 73#

\(val = normI(A)\), infinity norm of the matrix A (maximum row sum)

FROBENIUS = 70#

\(val = normF(A)\), Frobenius norm of the matrix A (square root of sum of squares).

TWO = 50#

\(val = \sqrt{max(\lambda(A^H A))}\), norm induced by the 2-norm of a vector. Also called the spectral norm.

class einsums.linalg.Transpose#

Transpose mode for a matrix operand, mapping 1:1 onto the BLAS op flag. Enumerators are the BLAS letters. None is avoided because it is a Python keyword.

N = 78#

op(A) = A (no transpose).

T = 84#

op(A) = A^T (transpose, no conjugation).

C = 67#

op(A) = A^H = conj(A)^T (conjugate transpose).

class einsums.linalg.Vectors#

Compute modes for the singular value decomposition.

Added in version 1.0.0.

Changed in version 2.0.0: The enum member names are now all caps to match the recommended style. The overwrite option is also removed since the input should be const and should not be overwritten.

ALL = 65#

Compute all vectors.

SOME = 83#

Compute some of the vectors. The number is the smaller of the number of rows and columns.

NONE = 78#

Don’t compute any vectors.