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 interchangesgetrfproduces, as something a graph can outlive.abs— Graph-aware magnitude:out := |A|. Real or complexAproduces realout. 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 ofsrcintodst.conj— Graph-aware in-place complex conjugate:A := conj(A). A no-op for real dtypes, matchingnumpy.conjon 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].dot— Python-friendly graph-aware dot: writes the result intoresult->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 ofsrcintodst.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 systemA * X = Bin place.getrf— LU-factorizeAin place, recording the row interchanges inpivots.getrs— SolveA * X = Bin place against a factorizationgetrfproduced.grouped_axpby— One node holding many independent AXPBYs:Y_i = alphas[i] * X_i + betas[i] * Y_ifor every entry.grouped_direct_division— One node holding many independent element-wise quotients:C_i = alphas[i] * (A_i ⊘ B_i) + betas[i] * C_ifor every member.grouped_direct_product— One node holding many independent element-wise products:C_i = alphas[i] * (A_i ⊙ B_i) + betas[i] * C_ifor 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^TwithB_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). ComplexAproduces realout. For realAit 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 intoresult->data()[0]. Backs the numpy-styleA.max(). Real dtypes only, since complex ordering is not meaningful; usenorm(MAXABS)for the largest magnitude.norm— Python-friendly graph-aware norm: writes the result intoresult->data()[0].outer_sum— Outer sum of N rank-1 vectors with per-axis coefficients.pow— Matrix power:A^alphavia eigendecomposition.qr— QR decomposition (returning):A = Q * R.real— Graph-aware real part:out := Re(A). ComplexAproduces realout. For realAit is a copy, since Re(x) == x, matching numpy.real. Dense or tiled.reshape— Graph-aware reshape: copyAintoout, which has the same number of elements in a different shape.scale— Graph-aware scale: multipliesAin place by the scalarfactor.scatter— Writesrcinto an arbitrary index selection ofdst.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 intoresult->data()[0].sum_axes— Graph-aware reduction: sumAoveraxes, writing the surviving axes tooutin 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-awareC = op(B)^T op(A) op(B), orop(B)^H op(A) op(B)withconjugate. A, B and C may be compile-time-rank matrices or runtime-rank tensors, as ingemm.trace— Trace of a square matrix:sum(A_ii). Returns the scalar.truncated_svd— Rank-ktruncated SVD (returning): keeps the topksingular triples ofA. Returns(U_k, S_k, Vt_k)withU_kof shape(m, k),S_kof shape(k,), andVt_kof shape(k, n).truncated_syev— Rank-ktruncated symmetric eigendecomposition (returning): keeps the topkeigenpairs of a real symmetricA. 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.Noneis avoided because it is a Python keyword.Vectors— Compute modes for the singular value decomposition.
Classes#
- class einsums.linalg.LuPivots#
The row interchanges
getrfproduces, 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:
getrfandgetrsboth bake a copy of theshared_ptrinto 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:
getrfwrites it,getrsreads it, and the hazard scan serializes the pair on that edge. Agetrsagainst a handle whose matchinggetrfwrites a different tensor has nothing holding the two together and is a bug in the caller.The buffer is sized by
getrfon the first execution and reused afterwards.
Functions#
- einsums.linalg.abs(out: Any, A: Any) None#
Graph-aware magnitude:
out := |A|. Real or complexAproduces realout. 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
axpybut also scales the destination bybetafirst. 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
srcintodst.For each axis k, copies
extents[k]elements starting atsrc_offsets[k]in src intodst_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, matchingnumpy.conjon 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].outis rank-1 with extentmin(A.dim(0), A.dim(1)), matching numpy’snp.diagon a matrix. A rectangularAis fine; the shorter axis wins.
- 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].resultis 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 likee = ½ Σ 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 bilinearsum A_i B_i. For real dtypes this coincides withdot. Backed bytrue_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_viewoverload 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
srcintodst.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_copycovers 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.
axesoptionally reorders the axes on the way out: source axis k lands on destination axis axes[k], sodst[…, 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_aandtrans_b(Python kwargs, defaultFalse) request the transpose of the corresponding matrix. All three tensors must be rank 2; a clearRankErroris 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 viaTensorHandle::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, defaultFalse) transposes A. A must be rank 2 and z, y must be rank 1; aRankErroris 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 computesA += alpha * X * Y^T: here the second vector is conjugated. Complex operands only; for real operands useger. Backed by linear_algebra::gerc (BLAS cgerc/zgerc).
- einsums.linalg.gesv(A: Any, B: Any) int#
Solve the linear system
A * X = Bin place.On return
BholdsXandAholds its LU factorization.Bmay be rank 1 (single right-hand side) or rank 2 (multiple right-hand-side columns). Returns the LAPACK info code: 0 on success, positiveiifAis singular at rowi.
- einsums.linalg.getrf(A: Any, pivots: LuPivots) int#
LU-factorize
Ain place, recording the row interchanges inpivots.On return
AholdsLandUin the LAPACK packing (the unit diagonal ofLis not stored) andpivotsholds the interchanges, sized to the order ofA. Unlikegesv, the factorization survives every solve made against it, so onegetrffeeds any number ofgetrscalls. Returns the LAPACK info code: 0 on success, positiveiifU(i,i)is exactly zero - the factorization is still complete, but a solve against it is meaningless.The same
pivotsobject must be handed to the matchinggetrs, and ordering rides onArather than on the pivots.
- einsums.linalg.getrs(A: Any, pivots: LuPivots, B: Any) int#
Solve
A * X = Bin place against a factorizationgetrfproduced.Ais the LU factorization andpivotsthe interchanges the matchinggetrfleft; both are READ, so the pair serves any number of right-hand sides and any number of replays.Bmay be rank 1 (a single right-hand side) or rank 2 (one per column), and on return holdsX. 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_ifor every entry.The grouped counterpart of
axpby, and the accumulating half of the patterngrouped_dotreduces 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
axpbythat 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_ifor 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. Everythinggrouped_direct_productsays 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_ifor 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_producta singledirect_productnode 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_pythoncall 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_gemmthere 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
gatherof 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 ofsrconce 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:
srcis(NQ, NU, NU)with the auxiliary axis fastest,X_iis(nu_i, nt_i)and column-contiguous, andC_iis(nq_i, nt_i, nt_i)wherenq_iandnu_iare the lengths of the member’s index lists. A member with any extent zero is a quick return, except that an emptyuselection 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_dotandgrouped_axpbydo 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_pfzero) 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^TwithB_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 productWthe size ofA_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 streamsA_ionce 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_iis(nq, na, na)with the auxiliary axis fastest,M_iis(nq, nk, na),P_iis(nk, na),S_iis(na, na), andC_iis(na, na), accumulated into (beta = 1semantics, so the node reads its destinations).P_i,S_iandC_imust be column-contiguous;A_iandM_imay 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 returnAholds eigenvectors as columns (whencompute_eigenvectors=True);Wholds the eigenvalues in ascending order.Wis real even thoughAis complex.
- einsums.linalg.imag(out: Any, A: Any) None#
Graph-aware imaginary part:
out := Im(A). ComplexAproduces realout. For realAit 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.Amust be rank 2 and square. Internally callsgetrffollowed bygetri; raisesRankErrorif the input rank is wrong and the LAPACK kernel raises ifAis singular.
- einsums.linalg.max(result: Any, A: Any) None#
Graph-aware maximum element (real dtypes), written into
result->data()[0]. Backs the numpy-styleA.max(). Real dtypes only, since complex ordering is not meaningful; usenorm(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
doubleresult tensor). UseNorm::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
resultwithresult(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
coefficientsis 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 equalvectors.size()andresult->dim(k)must equalvectors[k]->dim(0).
- einsums.linalg.pow(A: Any, alpha: Any, cutoff: Any = std::numeric_limits<typename AType::ValueType>::epsilon()) GeneralRuntimeTensor#
Matrix power:
A^alphavia eigendecomposition.Returns a freshly-allocated square matrix.
alphamay be negative; an optionalcutoffzeros out eigenvalues whose magnitude is belowcutoff * max|eig|before exponentiation (guards against near-singular inputs whenalpha < 0). Cannot be used during graph capture (returns by value);Ais left unmodified.
- einsums.linalg.qr(A: Any) tuple[GeneralRuntimeTensor, GeneralRuntimeTensor]#
QR decomposition (returning):
A = Q * R.Returns the tuple
(Q, R)whereQis orthogonal (or unitary for complex inputs) andRis upper-triangular. Cannot be used during graph capture;Ais left unmodified.
- einsums.linalg.real(out: Any, A: Any) None#
Graph-aware real part:
out := Re(A). ComplexAproduces realout. For realAit 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
Aintoout, which has the same number of elements in a different shape.row_majorpicks 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’sreshapedefaults 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
Ain place by the scalarfactor.
- einsums.linalg.scatter(dst: Any, src: Any, indices: list[list[int]]) None#
Write
srcinto an arbitrary index selection ofdst.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 toscatterrather 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-callableelement_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())), matchingelement_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 toabs, 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::Customnode otherwise. Stride-correct (works on slice/transpose views). Backs the numpy-styleA.sum()/A.mean().
- einsums.linalg.sum_axes(out: Any, A: Any, axes: list[int]) None#
Graph-aware reduction: sum
Aoveraxes, writing the surviving axes tooutin their original order.sumalready reduces a whole tensor to a scalar; this is the axis-wise form, numpy’sA.sum(axis=...).outmust have rankrank(A) - axes.size()with the extents of the axes not being summed.outis 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).Sis real even for complex inputs.UandVtare always present, and the user can post- filter for the “no vectors” case if needed. Cannot be used during graph capture (returns by value);Ais 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
svdfor large matrices; uses LAPACK’sgesdddriver. Returns(U, S, Vt)likesvd.jobcontrols whether the singular vectors are computed (ALL,SOME, orNONE). Cannot be used during graph capture (returns by value);Ais 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),Aholds the eigenvectors as columns;Wholds the eigenvalues in ascending order.Amust be rank 2 and square;Wmust be rank 1 with sizeA.dim(0). For the returning form (allocates fresh outputs) seesyev_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.Ais 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), orop(B)^H op(A) op(B)withconjugate. A, B and C may be compile-time-rank matrices or runtime-rank tensors, as ingemm.
- 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-
ktruncated SVD (returning): keeps the topksingular triples ofA. Returns(U_k, S_k, Vt_k)withU_kof shape(m, k),S_kof shape(k,), andVt_kof shape(k, n).Randomized algorithm with over-sampling factor 5, which requires
A.dim(0) >= k + 5. Smaller inputs raiseIndexErrorfrom the projection step. Results are approximate; expect small drift versus a fullsvd.Cannot be used during graph capture (returns by value);
Ais left unmodified.
- einsums.linalg.truncated_syev(A: Any, k: int) tuple[GeneralRuntimeTensor, GeneralRuntimeTensor]#
Rank-
ktruncated symmetric eigendecomposition (returning): keeps the topkeigenpairs of a real symmetricA. 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 raiseIndexErrorfrom the projection step. Results are approximate top-keigenpairs; expect small drift versus a fullsyev, especially for tightly clustered eigenvalues.Cannot be used during graph capture (returns by value);
Ais 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.
Noneis 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.