einsums.graph#
Note
This page is generated by apiary from the binding
annotations and the package’s Python source. Do not edit by hand.
Summary#
AntisymmetrizerExpansion— Lower a contraction’s permutation operator into an explicit contraction plus one permuted accumulation per term.AntisymmetrizerFolding— Collapse a permutation operator contracted against an antisymmetric operand into a scalar multiple.AntisymmetrizerLinearity— Pull a sum of antisymmetrized quantities inside one antisymmetrizer.AntisymmetryDetection— Establish, by reading the data, which of a permutation operator’s symmetries a bound input actually has.AntisymmetryInference— Tag the output of a permutation operator with the antisymmetry it unconditionally has.ApproximationRecord— One lossy rewrite that has been applied to a graph, and what it cost in accuracy.ApproximationTolerance— The comparison tolerance a set of approximation records implies.AxisTiling— Rewrite a program as a loop over slices of its free axes, under a memory cap.BackingRun— What one backing’s storage moved in a replay, counted where it moved.BasisTruncation— Truncate an index space to the natural orbitals a density says are occupied.BisectDriver— Run a program once per structural pass and report which one moved the answer.BisectReport— The whole run.BisectTrial— What one pass did to the numbers.CSE— Common Subexpression Elimination (CSE): merges two nodes that compute the same value – or one that is a fixed multiple of the other – and redirects readers of the duplicate onto the survivor’s output.CaptureContext— Thread-local capture context for recording operations into a graph.ConstantFolding— Constant folding: evaluates nodes whose inputs never change once, at pass time, and replaces them with no-ops.ContractionPlanning— Multi-objective contraction planning pass.CrossSpaceFinding— One index letter of one contraction binding two different index spaces.CrossSpaceValidation— Flag contraction letters that bind one operand’s slot against a slot of another space.DataflowExecutor— TaskPool dataflow executor, maximum overlap via continuations.DeadNodeElimination— Dead node elimination (DNE): removes producers whose every output is an unread graph-owned intermediate.Decision— One thing a pass did, declined or said, as a record.DeltaElimination— Eliminate contractions against a tagged Kronecker delta by index substitution.DiisAcceleratorF— Pulay DIIS extrapolation over a set of (amplitude, step) tensor pairs.DiisAcceleratorD— Pulay DIIS extrapolation over a set of (amplitude, step) tensor pairs.DiisAcceleratorC— Pulay DIIS extrapolation over a set of (amplitude, step) tensor pairs.DiisAcceleratorZ— Pulay DIIS extrapolation over a set of (amplitude, step) tensor pairs.DistributiveFactoring— Distributive factoring pass: factors out shared operands from accumulating einsums.ElementWiseFusion— Element-wise operation fusion: collapses directly consecutive Scale or axpby ops on the same tensor into a single node.EventLog— An observer that keeps every event, for reading after the replay: the way to observe a replay from Python, whose callbacks would serialize the executors on the GIL.ExecutionEvent— One thing that happened while a replay ran.ExecutionObserver— What hears a graph’s replays as they run, once attached withGraph::set_observer.Executor— Abstract base class for graph execution backends.Fact— A named quantity a decision carries: a block size, a byte count, a run count.FactorizationPass— Replace a tagged tensor by a provider’s factors, and re-associate around them.FactorizationProvider— A way of rewriting one kind of tensor as a product of factors.FactorizationRegistry— The providers a process knows about.GateFlags— An array of conditional gates a graph reads without calling back into its caller.Graph— A directed acyclic graph (DAG) of tensor operations.GrowthClass— How a space’s extent grows with the size of the system.IndexSpace— The semantics of one index space, and nothing else.InplaceOptimization— InplaceOptimization pass: in-place storage merging for elementwise consumers.LaplaceTransform— Substitute a quadrature for a tagged energy denominator and decouple its consumer.LayoutAssignment— Choose the storage order of every graph-owned intermediate so contractions read flat.LinearCombinationContractionFolding— Fold transpose-paired contractions into one (the CCSD “2J−K” idiom).LoopInvariantHoisting— Loop invariant hoisting: moves body operations whose inputs never change across iterations to run once before the loop.ManifestEntry— One named slot of a graph’s interface: an operand the graph does not own.Materialization— Materialization pass: give every deferred (shell) tensor a Materialize (and optional Initialize) lifecycle node so it is allocated at the right point during execution.MemoryPlanning— MemoryPlanning pass: liveness analysis, memory statistics, and the planned host arena.MetricFitFactorization— Offer a four-index tensor as a metric-fitted product of one three-index factor.MultiTermFactorization— Jointly choose contraction orders and shared intermediates over one region.NaryEinsumStep— One contraction of anplan_nary_einsumplan.NaturalAuxiliaryFactorization— Offer a three-index tensor over a truncated auxiliary index.NodeRun— One node’s share of a replay.NodeTiming— Per-node timing entry.OpenMPExecutor— OpenMP task-based executor, launches independent nodes in parallel.OptimizerPass— Abstract base class for optimization passes over a computation graph.PassManager— Manages an ordered sequence of optimization passes.PermuteFusion— Permute-into-einsum fusion: absorbs an axis-reordering Permute into the subscript of the Einsum that reads it.Pipeline— A pipeline of sequential stages with optional iterative loops.ProvenancePropagation— Propagate provenance tags across identity-preserving operations.ProvenanceTag— What a tensor is, for a pass that has to recognize it rather than merely size it.RegionIdentity— Raise every region and lower it unchanged.RegionRewrite— Base class for a pass that rewrites regions throughTensorExpr.Reorder— Memory-aware topological sort: reschedules independent nodes so the ones that free the most memory run earliest.RunMetrics— What the last replay of a graph did, asGraph::last_runreports it.ScaleAbsorption— Scale-elimination pass: removes a Scale by deleting it (dead) or folding its factor into a consumer’s prefactor (live).ScalingAnalysis— Report how a program scales: every contraction’s cost polynomial, and what limits it.ScratchPrivatization— Break false dependencies from reused scratch buffers by renaming each reuse onto its own clone.SequentialExecutor— Sequential executor, executes nodes in topological order.SerializabilityBlocker— One node that blocks a graph from being saved, and what blocks it.SlabStreaming— Read a backed tensor a slab at a time instead of loading it whole.SpaceDim— One dimension of a declared tensor, given as an index space rather than a number.SpaceId— Opaque handle to a space held by aSpaceRegistry.SpacePropagation— Infer per-slot index spaces on graph intermediates.SpaceRegistry— Spaces, the relations declared between them, and the policy table keyed by their names.SpaceTiling— One axis of a declared TILED tensor: what it means, and how it is cut up.StreamContractionFusion— Fuse contractions that stream the same large tensor into one pass over it (the SCF “J and K from one TEI read” idiom).SymmetrizedAccumulation— Fold the CCSD permutational-symmetrization idiom \(r2 \mathrel{+}= s\,(t + P(t))\).SymmetryPropagation— Phase 3 of the symmetry plan: infer symmetry on graph intermediates.TensorBacking— The storage behind a tensor the graph reads, or writes, but never holds whole.ThcFactorization— Offer a four-index tensor as a fitted chain over two grid indices.WaggleBridge— An observer that labels the profiler’s zones with what the graph was doing in them.Workspace— Owns tensors that persist across multiple Graphs and Pipelines.batched_gemm— Emit one blas::gemm_batch over a batch of independent GEMMs:C_i = alpha * op(A_i) op(B_i) + beta * C_ifor every i.batched_gemm_blocked—batched_gemmwhere the destinations are uniform-shaped blocks of a single tensor, described by their offsets rather than enumerated as views.custom— No-dependency custom node, Python-friendly overload.diis_add_pair— Register one(amplitude, step)pair with a DIIS accelerator.diis_step— Take one DIIS step over an accelerator’s registered pairs.duplicate_materializations— Tensors with more than one Materialize node, anywhere ingraph'stree.eager_einsum_intermediate_limit— The most elements an eager einsum over several operands lets a partial product hold.fixed— An axis whose size is a number and whose meaning is nothing.global_factorization_registry— The process-wide provider registry.global_space_registry— The process-wide space registry.grouped_batched_gemm— Emit one blas::gemm_batch_grouped over independent GEMMs whose shapes need NOT agree:C_i = alpha * op(A_i) op(B_i) + beta * C_i.grouped_batched_gemm_blocked—grouped_batched_gemmwhere the destinations are blocks of existing tensors, described by a base and an offset rather than enumerated as views.last_dispatch_route_name— The kernel route the most recent contraction on this thread took, as a string.load_graph_file— Readpathback as a runnable graph, throwing on failure.load_graph_file_into— Readpathback againstregistry, throwing on failure. The Python spelling.make_approximation_record— Build anApproximationRecordin one call.make_index_space— Build anIndexSpacefrom its parts.make_provenance_tag— Build aProvenanceTag.permute_view— Python-friendly transpose / axis-permutation view.plan_nary_einsum— The cheapest order to contract an einsum over several operands two at a time.plan_nary_einsum_with_spaces— The cheapest order to contract an einsum’s operands, ranked by the index spaces they are annotated with.save_graph_file— Writegraphtopath, throwing on refusal.stranded_materializations— Graph-owned intermediates that are materialized and that nothing reads or writes.tile_view— Record a dense, parent-aliasing view of a single tile.tiles— A tiled axis with a partition and no space.validate_graph_ir_file— Checkpath, throwing with every problem when it is not valid.view— Python-friendly wrapper overview_runtime.view_indexed— Python-friendly indexed view supporting rank-reducing integer indices.views— Batchedview_indexed_python: record N views of one parent in one call.ApproximationEffect— What a lossy pass’s tolerance is a bound ON.ApproximationOrigin— Where a bound’s number came from.BisectMode— How many passes a trial turns on at once.ChainPricing— What ContractionPlanning prices a bracketing against.CrossSpaceSeverity— How much aCrossSpaceFindingis worth acting on.DecisionKind— Whether a pass applied something, declined a candidate, or only had something to say.EventKind— What anExecutionEventreports.Factor— Whether to let the cost model decide that a group is worth factoring.OpKind— Identifies the kind of operation a node represents.Tristate— Answer to a relation query that may simply not be known.
Classes#
- class einsums.graph.AntisymmetrizerExpansion#
Lower a contraction’s permutation operator into an explicit contraction plus one permuted accumulation per term.
A spec may name a permutation operator (
PermutationOperator), as incg::einsum("i,j,a,b <- P(ij) P(ab) i,m,a,e ; m,b,e,j", 1.0, &r2, 1.0, t2, W);and a node carrying one already computes the right answer without this pass:
dispatch::string_einsumcontracts into a temporary and accumulates the terms out of it. What it cannot do is own that temporary. It is astd::vectorsized from C on EVERY call, which for an \(o^2v^2\) residual term is an allocation per replay and, at production dimensions, an allocation far too large to make per replay.This pass rewrites the site into nodes the graph owns:
einsum(spec without the operator) -> tmp // tmp = ab_pf * (A (x) B) permute(term_0 <- c_indices) -> C // C = c_pf * C + sign_0 * tmp permute(term_t <- c_indices) -> C // C = C + sign_t * P_t(tmp)
The temporary becomes an ordinary intermediate, so Materialization, MemoryPlanning and the lifetime passes treat it as they treat every other one, and the allocation happens once instead of per call.
The contraction cannot write C directly: the permuted accumulations would then read what they are writing. C’s own prefactor rides on the FIRST term, which is what keeps it applied exactly once rather than once per term, and the identity term is always first so that term is the one that may overwrite.
What this does not do
A
OpKind::Permutenode carrying an operator is LEFT ALONE. It needs no temporary, because every term reads a source the operation never writes, so lowering it would replace one node with N that do exactly the same work in the same order. That is a node-count regression with nothing bought: the N permutes share one source and one destination, so there is nothing for CSE to merge and nothing for PermuteFusion to fold. The whole-tensor (T) antisymmetrizer inexamples/toy/ccsd_t_spinorbital_toy.pyis the case, where it would turn two nodes back into eighteen.Ordering
Early in the graph-transforming group, ahead of ConstantFolding, so everything downstream sees the lowered form: CSE and DeadNodeElimination over the emitted nodes, LoopInvariantHoisting over the temporary’s construction, and MemoryPlanning over its lifetime. Recurses into subgraphs, because a CCSD residual is captured as a loop body.
Example
cg::Graph graph("ring"); { cg::CaptureGuard const capture(graph); cg::einsum("i,j,a,b <- P(ij) P(ab) i,m,a,e ; m,b,e,j", 1.0, &r2, 1.0, t2, W); } graph.apply(cg::PassManager::create_default()); // one einsum node becomes an einsum into scratch plus four accumulating permutes
- class einsums.graph.AntisymmetrizerFolding#
Collapse a permutation operator contracted against an antisymmetric operand into a scalar multiple.
When \(W\) is antisymmetric under every permutation \(P[G]\) sums over,
\[\sum_x W(x)\,P[G](V)(x) \;=\; N \sum_x W(x)\,V(x)\]with \(N\) the operator’s term count. Substituting \(y = \sigma_t(x)\) turns each term into \(\mathrm{sign}_t \sum_y W(\sigma_t^{-1}(y))V(y)\), and \(W\)’s antisymmetry makes that \(\mathrm{sign}_t^2 \sum_y W V\), so every term contributes the same thing.
The saving is the whole antisymmetrizer: \(N-1\) permuted accumulations over a tensor the size of the contraction’s operands, replaced by one scalar multiply. It is the transformation examples/toy/ccsd_t_spinorbital_toy.py performs by hand between its “naive” and “folded” (T) spellings, where its own table puts it at about a third of the whole-tensor runtime.
What it matches
a
OpKind::Dotwhose operands areAandB;Bwritten by exactly one node, which carries an operator with a ZERO destination prefactor;Acarrying aTensorHandle::symmetry_hintthat states antisymmetry on every axis the operator permutes;nothing between the two nodes writing either operand.
The rewrite repoints the contraction at the operator’s SOURCE and inserts a scale by \(N\alpha\) on the result, with \(\alpha\) the operator node’s own scale (\(B = \alpha P[G](V)\)), conjugated when the contraction is a
dotcandBis its conjugated operand. A real result under an imaginary \(\alpha\) is left alone. The operator node is left standing;DeadNodeEliminationremoves it when nothing else reads it, which in the toy’s naive (T) is true ofVand false ofW, matching by construction what the hand-written folded spelling does.Where the premise comes from
AntisymmetryInference, which must run first, and behind itAntisymmetryDetectionfor any premise that is not structural. Together they reach both arms: an operator whose groups are all singletons carries its antisymmetry unconditionally, and a coset form carries it once its operand is known antisymmetric within each group. See DESIGN-permutation-operator-folding.md.What the guard covers, and what it does not
The rewrite is justified by the tensors bound when the pass ran, so it emits an
OpKind::Setupbody that re-checks those facts and throws naming the tensor. A BIND clears that body’scomputedflag, so the check runs once per bound problem.An IN-PLACE mutation of a checked input is not a bind, and the graph cannot see it: the tensor belongs to the caller, no node of this graph writes it, and its address does not change. So a caller who overwrites the contents of a tensor this pass validated, and then replays without rebinding, gets the folded arithmetic against data nothing re-checked. That is the boundary, stated rather than papered over, and
Graph::invalidate_setupis the way across it: it puts the guard back to work on the next execute.The shape this arises in is narrower than it sounds. A quantity the graph itself updates is written by some node, and
AntisymmetryDetectiononly ever looks at tensors NOTHING writes, so an amplitude a captured iteration updates was never a premise in the first place.Ordering
Before
AntisymmetrizerExpansion, which strips the operator and so removes the thing this matches on.
- class einsums.graph.AntisymmetrizerLinearity#
Pull a sum of antisymmetrized quantities inside one antisymmetrizer.
A permutation operator is LINEAR, so
\[a\,P[G](B) \;+\; s\,\bigl(c\,P[G](A)\bigr) \;=\; P[G]\bigl(a B + s c A\bigr)\]and a graph that antisymmetrizes two things and adds them can antisymmetrize once instead.
Why it matters more than the node it saves
On its own the rewrite trades one permuted-accumulation sweep for an add, which is worth having and is not the point. The point is that the sum’s producer becomes an OPERATOR again.
AntisymmetrizerFoldingmatches a contraction whose operand was written by an operator, and a residual writes V := W + P(Xd), so the operand’s producer is a linear combination and the fold cannot see the operator standing behind it. This puts it back where the fold can reach, which is what turns an N-term antisymmetrizer into a scalar multiply.It is the same move the hand-written folded spelling of examples/toy/ccsd_t_spinorbital_toy.py makes when it accumulates Xc := Xc + Xd and antisymmetrizes once.
What it matches
a tensor written exactly twice: an operator with a ZERO destination prefactor, then an Axpby accumulating another tensor into it;
that other tensor written exactly once, by an operator with the SAME groups and a zero destination prefactor;
both tensors graph-owned intermediates untouched by a child sub-graph.
The first operator’s source is replaced by a freshly built sum, its prefactor folded into that sum, and the accumulation deleted. The second operator is left standing, because a residual reads it separately (the toy divides it by the energy denominator) and
DeadNodeEliminationremoves it when nothing does.
- class einsums.graph.AntisymmetryDetection#
Establish, by reading the data, which of a permutation operator’s symmetries a bound input actually has.
AntisymmetryInferenceproves what an operator’s output has STRUCTURALLY, which reaches only the singleton-partition case. The facts a coupled-cluster residual needs are about the problem rather than the graph: that the amplitudes are antisymmetric in a pair of slots, that an energy denominator is invariant under the permutations the residual applies. Nothing derives those, and this pass does not ask a user to assert them either. It looks.For each operator in the graph it forms two candidate descriptors over the operator’s output axes, and tests them against the bound inputs of matching shape:
within-group antisymmetry, which is the precondition a coset operator’s output needs before it carries any antisymmetry of its own;
invariance under each permutation the operator sums over, which is what lets an elementwise division by that tensor preserve a numerator’s antisymmetry.
Whatever holds is recorded on
TensorHandle::symmetry_hint, which is graph metadata. The backing tensor is never written, so a user’s declared symmetry, or absence of one, is left exactly as it was.Only inputs, and why that is not a limitation but a correctness gate
A tensor written by some node in this graph holds, at optimize time, whatever it was initialized to. Graph-owned scratch is typically ZERO, and a zero tensor satisfies every symmetry there is. Tagging one would record a fact that is true of the buffer now and false of the value the graph will put in it, which is the most direct route to a wrong answer this design has. So a candidate must have NO writer in the graph: it is a bound input, and what is in it at optimize time is what the contraction will read.
Cost
One pass over a candidate per generator that HOLDS, and effectively nothing per generator that does not, since
check_symmetrystops at the first violation: measured at 1.47 ns an element against 0.4 microseconds for a whole rank-6 tensor whose generator fails. Probing many candidates is therefore cheap and only a real symmetry costs a sweep.The premise is DATA, which constrains what may be built on it
A fact established here describes the tensors bound right now. A rebind replaces them, and ContractionPlanning states the house rule this runs into: a measurement may found a hint, not a premise. Anything that REWRITES arithmetic on the strength of one of these facts therefore has to be re-checked per bound problem, which is what
OpKind::Setupexists for. See DESIGN-permutation-operator-folding.md.
- class einsums.graph.AntisymmetryInference#
Tag the output of a permutation operator with the antisymmetry it unconditionally has.
A node whose spec names a permutation operator (
PermutationOperator) produces a tensor with structure, and this records what that structure is so a later pass can rewrite arithmetic against it. Today the consumer isAntisymmetrizerFolding.The rule, and the narrow case it covers
For an operator whose groups are all SINGLETONS, the expansion is \(P = \sum_\sigma \mathrm{sign}(\sigma)\,\sigma\) over the whole symmetric group on its letters, so \(\tau P = \mathrm{sign}(\tau) P\) for every transposition and the output is antisymmetric in those axes whatever the operand was.
For an operator with a group of two or more this is FALSE, and measurably so. P(i/jk) applied to arbitrary rank-3 data is antisymmetric under none of (ij), (ik) or (jk): a coset form carries the antisymmetry only when its operand already has it within each group, which is the same precondition the operator’s well-definedness rests on. Those operators are DECLINED here rather than tagged, and reaching them needs a fact about the operand that this pass has no way to establish. See DESIGN-permutation-operator-folding.md.
Soundness
Three gates, all load-bearing:
the destination prefactor must be ZERO, since with a nonzero one the result is the previous contents plus an antisymmetric part, which is not antisymmetric;
the tensor must have exactly one writer in this graph and no reference from a child sub-graph, which is
EscapeAnalysis, shared withSymmetryPropagationrather than re-derived;only graph-owned intermediates are tagged, never a user’s tensor.
Ordering
Before
AntisymmetrizerExpansion, which strips the operator and so destroys the evidence this rule reads. That is also why this is a separate pass fromSymmetryPropagation, which runs after Materialization for a different purpose and would find nothing left to infer from.Writes only
TensorHandle::symmetry_hint, which is graph metadata, so it needs no backing storage and can run before anything is materialized.
- class einsums.graph.ApproximationRecord#
One lossy rewrite that has been applied to a graph, and what it cost in accuracy.
Accumulated on the
Graphand SAVED with its structure, because it is a statement about what the graph now computes rather than about how it runs: a caller reading a result off a loaded graph is entitled to know that the energy is DF at 1e-5, and no machine can recover that from the node list.It is three things at once. Provenance for the user, the input to the composition rule that lets a second lossy pass decide whether it may apply, and the trigger that widens a differential test’s tolerance from exact to whatever the records say.
See also
Graph::note_approximation
See also
Graph::approximation_tolerance
Added in version 2.0.0.
- pass_name: str#
The pass that applied the rewrite, by
OptimizerPass::name.Not spelled
pass, which is what it wants to be called and is a Python keyword: the field would bind to a name no Python source can write down. The saved key matches this spelling rather than the shorter one, so the file and the type do not need a translation nobody would remember was there.
- tolerance: float#
The knob the pass was ASKED for, e.g. a
thc_epsilonof 1e-5. Recorded besideboundrather than instead of it: a pass may well meet its target with room to spare, and a composition rule that read the target would spend accuracy nobody used.
- effect: ApproximationEffect#
What
boundis a bound on.
- bound: float#
The effect the pass STATES it had, in
effect’s units. This is what composes and what a tolerance-aware comparison widens by.
- origin: ApproximationOrigin#
Whether
boundwas computed or claimed. Defaults toApproximationOrigin::Asserted, which is also how a file written before this field existed is read: a number cannot be promoted to evidence by a newer build reading it.
- outputs: list[str]#
Manifest names the bound applies to. EMPTY means every output, which is the honest answer for a pass that rewrote something feeding all of them.
- spaces: list[str]#
Index-space names the rewrite involved, by NAME for the reason every other saved annotation holds names: an id means nothing in another process.
- setup: str#
Label of the setup node the rewrite created, or empty when it created none. A factorization emits its fitting into one, and the record is where the two are tied together for anyone asking what produced these factors.
- measurement: str#
The TENSOR whose value after a replay is this rewrite’s MEASURED error, by name, or empty when the rewrite measures nothing.
A record is written once, at optimize time, so
boundis what the structure claims and cannot be what a particular bind found. What a bind can leave behind is a value in the graph, and this is where the record says which one, so a caller holding a record does not have to know how the pass spells its diagnostics.A tensor rather than a parameter, and that is a correction rather than a preference: the
ParamTableis integer-valued, so a residual below one truncates to zero there and a number that cannot represent what it measures is not a measurement. The precedent that works is the error tensor a Laplace quadrature already writes.It is also the whole of the rule for a rewrite INSIDE A LOOP. A fit re-fitted at every amplitude update writes this tensor once per iteration, so what stands in it when the solver stops is the fit’s error at the LAST iteration, which is the iteration the converged answer came out of. There is no per-iteration history and there should not be: the intermediate fits are error in a quantity nobody kept.
- class einsums.graph.ApproximationTolerance#
The comparison tolerance a set of approximation records implies.
Two numbers rather than one because the effects do not share units: an absolute bound widens the absolute side of a comparison and a relative one widens the relative side. Which is which is
is_absolute_effect, in one place.Both zero means the graph carries no records, which is exact mode and today’s behavior.
See also
Graph::approximation_tolerance
Added in version 2.0.0.
- class einsums.graph.AxisTiling#
Rewrite a program as a loop over slices of its free axes, under a memory cap.
cg::PassManager manager; auto tiling = std::make_shared<cg::passes::AxisTiling>(); tiling->set_memory_cap(4096); manager.add(tiling); graph.apply(manager);
A member of
PassManager::create_default, after the algebraic rewrites. By default the cap is what the--einsums:max-memoryoption leaves after every other tensor of the graph, so in the default pipeline the pass streams only a program that would not fit; on one that fits it does no more than run a provably symmetric region as a triangle where that is cheaper. A caller with a smaller footprint to live inside sets a cap of its own.Added in version 2.0.0.
- set_memory_cap(bytes: int) None#
Override the cap for this pipeline, in bytes.
Beats
option::GraphTilingMemoryCap, which is the two-level shape every other per-pass knob in this module has.Added in version 2.0.0.
- Parameters:
bytes – Largest a single live intermediate may be. Zero disables the pass, and a negative value derives the cap from the
--einsums:max-memoryoption and the graph’s other tensors.
- set_block_extent(extent: int) None#
Pin the block extent of a triangle’s two axes.
A triangle’s block is priced from the machine’s measured kernel rates, so the block it chooses moves between machines. A test that checks the emission at a given block pins it here. A pinned block that does not fit the memory the region may take declines the triangle.
Added in version 2.0.0.
- Parameters:
extent – The block, two or more; zero lets the cost model choose, which is the default.
- use_reference_cost_model() None#
Price against the cost model’s built-in rates instead of the detected machine’s.
The pass prices each candidate from the machine’s measured kernel rates, so where two candidates are close the one it chooses moves between machines. With the built-in rates the decision is the same on every machine, which is what a test that checks the choice needs.
Added in version 2.0.0.
- memory_cap: int#
The cap in force: this pipeline’s override, or the option’s value.
Added in version 2.0.0.
(read-only)
- num_tiled: int#
How many regions the last apply tiled.
The other getters describe the first of them, the region around the largest intermediate;
explainnames every one.Added in version 2.0.0.
(read-only)
- axis_names: list[str]#
The sliced axes of the last decision, named
tensor[position].Added in version 2.0.0.
(read-only)
- axis_letters: list[str]#
The index letter each sliced axis carries, where a contraction names one.
Added in version 2.0.0.
(read-only)
- slice_count: int#
How many slices the chosen axes cut the program into.
Added in version 2.0.0.
(read-only)
- depth: int#
How many slices one iteration of the emitted loop handles.
Added in version 2.0.0.
(read-only)
- largest_before: int#
The largest single intermediate any examined graph declared before the rewrite, in bytes.
Added in version 2.0.0.
(read-only)
- largest_after: int#
The largest single intermediate the body declares after the rewrite, in bytes.
Added in version 2.0.0.
(read-only)
- streamed: list[str]#
The intermediates the rewrite streams, by name.
Added in version 2.0.0.
(read-only)
- class einsums.graph.BackingRun#
What one backing’s storage moved in a replay, counted where it moved.
Every read and write of a backing goes through the graph’s fill and store, whichever pass put them there: a whole load, a slab a contraction streams, a box a loop’s view names, a whole store after the last writer, a slab a streamed producer writes. A read or a write counts once per call, whatever its size.
Added in version 2.0.0.
- class einsums.graph.BasisTruncation#
Truncate an index space to the natural orbitals a density says are occupied.
See also
BasisTruncation.hpp for the construction and for what chemistry calls it
Added in version 2.0.0.
- static register_fno_space(graph: Graph, outer: str = 'vir', fraction: float = 0.5) SpaceId#
Register the truncated space in
graph'sown registry, insideouter.The same shape
NaturalAuxiliaryFactorization::register_naf_spacehas, and the same three statements: the space itself, its containment in the space it truncates, and the scale order beside it. Containment is what says a contraction over the subspace is a RESTRICTION of the one over the parent rather than an unrelated quantity; the scale order is what lets a cost comparison rank the two.The typical extent is derived from
outer'satfractionof it, for the reason the auxiliary truncation’s is: a space declared smaller than another must carry a typical extent when that other one does, or the cost comparison’s second rung ranks the restricted form as unmeasurable rather than as cheap.Register
outerBEFORE calling this.- Parameters:
graph – The graph whose registry gains the space.
outer – The name of the space being truncated, or empty for no relation.
fraction – What fraction of
outer'stypical extent the truncated space is expected to be. A half is the conventional frozen-natural-orbital saving.
- Returns:
The space’s id in that registry.
- Raises:
Exception – When
fractiondoes not lie strictly between zero and one.
- set_amplitudes(amplitudes: Any) None#
Hand the pass the first-order amplitudes the density is built from.
Supplied to the PASS rather than found in the graph, which is the shape
LaplaceTransformhas for its energies andMetricFitFactorizationfor its three-index tensor, and for the same reason: a caller who computed the amplitudes outside the graph has a tensor no node mentions, and the graph has never seen it.It becomes an interface tensor of the transformed graph, under its own name, because the setup body captures it. That is what lets a saved graph re-truncate at a new geometry.
- Parameters:
amplitudes –
t[i,a,j,b], rank 4, with the virtual axes second and fourth. Its storage must outlive every replay, since the setup body reads it on each bind.- Raises:
Exception – When
amplitudesis not a rank-4 tensor whose two virtual axes agree.
- set_fock(fock: Any) None#
Hand the pass the Fock block over the space being truncated.
Needed because the kept natural orbitals are not canonical: their Fock block is not diagonal, so an energy denominator built from the old orbital energies would be wrong. Diagonalizing it inside the subspace is what restores a diagonal denominator and produces the new energies.
- Parameters:
fock –
F[a,b]over the full virtual space, rank 2 and square.- Raises:
Exception – When
fockis not a square rank-2 tensor.
- set_occupied_energies(energies: Any) None#
Hand the pass the orbital energies of the space the amplitudes’ other axes run over.
What it is for, since the construction does not need it
The record this pass writes carries \(E_{MP2}(\text{full}) - E_{MP2}(\text{fno})\) as its measured effect, and the two energies are what needs these. The integrals are not asked for separately because the amplitudes already carry them: a first-order amplitude is the integral over its denominator, and the denominator is these energies against the diagonal of the Fock block the pass already holds.
A projection with no way to measure its own effect is declined rather than recorded with a bound nobody computed, so these are required to PROJECT and not to build the space.
- Parameters:
energies –
eps[i], one per occupied orbital, rank 1.- Raises:
Exception – When
energiesis not rank 1 or does not have one entry per occupied axis of the amplitudes. Set the amplitudes first.
- set_occupation(occupation: float) None#
Override
einsums:graph:fno-occupationfor this pipeline.- Parameters:
occupation – Natural orbitals whose occupation exceeds this are kept.
- Raises:
Exception – When
occupationis not finite or is negative.
- set_virtual_space(name: str) None#
The name of the space this truncates.
- Parameters:
name – An index-space name, e.g.
"vir".
- transformation() Any#
The transformation the setup writes,
Uover the full space by the truncated one.The pass’s own tensor rather than the caller’s, because its second extent is decided by the pass and a caller cannot size a buffer for a count they do not yet know. It becomes an interface tensor of the transformed graph under
transformation_name.- Returns:
The tensor. Empty until the pass has run; written on every bind after that.
- energies() Any#
The orbital energies of the truncated space, ascending.
- Returns:
The tensor. Empty until the pass has run; written on every bind after that.
- static transformation_name() str#
The interface name
transformationis bound under.- Returns:
"fno_transformation".
- static keep_matrix_name() str#
The interface name the rectangular selection matrix is bound under.
- Returns:
"fno_keep". See the file note on why the selection is a contraction.
- static projected_name(name: str) str#
What the setup writes the projection of
nameinto.Not a manifest entry, and the difference is the whole of the contract
A manifest entry is something a bind must SUPPLY. These are graph-owned intermediates whose value the setup supplies and which nobody may bind. What a rebind supplies is the UNTRUNCATED tensor, under its own name for whatever else reads it and under
projection_input_namefor the projection to read.- Parameters:
name – The name of the tensor being projected.
- Returns:
"<name>@fno".
- static projection_input_name(name: str) str#
The interface name the projection reads
nameunder.The projection is captured, so what it reads becomes an interface tensor of the transformed graph. The caller’s own algebra no longer reads that tensor at all, so naming the projection’s copy is what keeps the untruncated tensor bindable; a rebind supplies the same tensor under this name. The same shape a fit that reads the tensor it replaces already has.
- Parameters:
name – The name of the tensor being projected.
- Returns:
"<name>@fno_in".
- occupations: list[float]#
The occupations the last run read off the density, largest first.
(read-only)
- projected: list[str]#
The names the last run projected, in the order they were projected.
(read-only)
- correction: float#
The MP2 energy the truncation removed, \(E_{MP2}(\text{full}) - E_{MP2}(\text{fno})\).
The record’s measured quantity rather than an extra output: a program that wants the corrected number adds this to whatever the correlated method produced in the truncated space, which is the same place the density-fitting and quadrature effects already compose.
(read-only)
- class einsums.graph.BisectDriver#
Run a program once per structural pass and report which one moved the answer.
Example (C++)
cg::BisectDriver driver([&](cg::Graph &graph) { // Capture the program. Fresh tensors every call: the driver runs this once per trial and // the trials must not see each other's writes. auto &T = graph.declare_runtime_tensor<double>("T", {n, n}, true); cg::CaptureGuard const capture(graph); cg::einsum("i,j <- i,k ; k,j", 0.0, &T, 1.0, A, B); cg::einsum("i,l <- i,j ; j,l", 0.0, &C, 1.0, T, D); }); auto const report = driver.run(); if (!report.clean()) { std::cout << report.to_string(); }Limitations
The builder must produce an equivalent program on every call, with tensors it does not share between calls. A builder that closes over one output buffer hands every trial the previous trial’s answer as its starting state, which reports the FIRST pass as the culprit whatever the truth is.
Only interface outputs are compared. A pass that changes a graph-internal intermediate and leaves every output alone is reported as clean, which is correct: nothing observes it.
A trial that throws is recorded and does not stop the run, because a pass that cannot run is itself a finding and the passes after it are still worth trying.
- __init__(builder: Callable[[Graph], None]) None#
The spelling Python gets: the same builder, taking a POINTER.
The difference is not cosmetic and is not a preference. Handing a C++ object to a Python callable goes through pybind’s default conversion, which for an lvalue REFERENCE resolves to copy, and
Graphis deliberately non-copyable; the call fails at run time with a message about a return value policy, on a constructor that bound perfectly. For a POINTER the same default resolves to reference, which is what is wanted: Python gets a non-owning view of the graph the driver owns.Warning
The view is valid only for the duration of the call. A Python builder that stashes the graph it was handed is holding a dangling pointer once the trial ends.
- Parameters:
builder – Called once per trial with the graph to capture into. Never null.
- set_passes(passes: list[OptimizerPass]) None#
Try these passes instead of the default pipeline’s structural ones.
The primary use, rather than an escape hatch: bisecting the pipeline a caller is ACTUALLY running is what answers their question, and
driver.set_passes(pm.passes())is how that is spelled. It is also the only way to reach a pass that is off by default, since a driver that switched one on would be testing a configuration nobody runs.- Parameters:
passes – The passes to try, in the order they would run.
- set_mode(mode: BisectMode) None#
One pass per trial, or passes one through k. See
BisectMode.- Parameters:
mode – The mode.
- set_bound_scale(scale: float) None#
Multiply every tier bound by
scale.For the caller whose accumulation is long enough that the default is tight, and for the one who wants to see how much headroom a clean run actually had. Refuses a non-positive scale: a bound of zero would report every re-associating pass as wrong.
- Parameters:
scale – The multiplier.
- Raises:
Exception – If
scaleis not positive and finite.
- run() BisectReport#
Run the baseline and every trial.
- Returns:
The report.
- class einsums.graph.BisectReport#
The whole run.
- first_divergence: int#
Index into
trialsof the first pass that diverged.FIRST rather than worst: in cumulative mode every later trial inherits the earlier one’s damage, so the largest gap is almost never the culprit.
(read-only)
- baseline_ok: bool#
Whether the unoptimized run produced something to compare against. When false nothing else here means anything, which is why it is asked first.
- trials: list[BisectTrial]#
One per pass tried, in pipeline order.
- class einsums.graph.BisectTrial#
What one pass did to the numbers.
- modified: bool#
Whether the pass reported changing anything. A pass that did not fire cannot be the cause of a divergence, and saying so is the difference between “cleared” and “never ran”.
- nonfinite_disagreement: bool#
The two runs disagree about WHERE the non-finite values are, which no norm describes.
- class einsums.graph.CSE#
Common Subexpression Elimination (CSE): merges two nodes that compute the same value – or one that is a fixed multiple of the other – and redirects readers of the duplicate onto the survivor’s output.
Detects pairs of nodes with identical OpKind, identical input TensorIds (in order), the same number of outputs, and OpData (EinsumDescriptor / AxpbyDescriptor / ScaleDescriptor / PermuteDescriptor / BatchedGemmDescriptor) that agrees on index patterns, conj flags, and the destination prefactor. The later duplicate is deleted; every downstream reader of its output is redirected – in both the TensorId metadata (so liveness passes see the survivor’s buffer as live) and via Graph::redirect_slot (so any already-baked executor lambda reads the survivor’s result at execute time). Redirections propagate through all remaining nodes’ input lists, so multi-level CSE resolves in a single pass.
Proportional duplicates
The two nodes need not agree on the SOURCE prefactor, the one their result is linear in (einsum’s ab_prefactor, axpby’s alpha, permute’s and batched-gemm’s alpha). When they differ by a factor r that is an exact power of two – so (r*x)*y and x*(r*y) agree bit for bit and no arithmetic changes – the duplicate is eliminated and r is multiplied into every reader’s own prefactor instead. CCSD’s tau and tau-tilde are the motivating shape: the same t1 x t1 outer product differing only by a 0.5. Ratios that are exactly representable but not powers of two are declined, so the result never depends on which of two proportional nodes the pass happened to keep.
Example (proportional)
cg::einsum("ij <- ik ; kj", 0.0, &P, 1.0, A, B); // survivor cg::einsum("ij <- ik ; kj", 0.0, &Q, 0.5, A, B); // Q == 0.5 * P cg::einsum("ij <- ik ; kj", 0.0, &out, 1.0, Q, F); // reader of the duplicate // After CSE: Q's producer is gone and the reader's ab_prefactor is 0.5.In the default pipeline (populate_default; also the O1 cleanup cluster in PassManager::create_for). Runs after PermuteFusion so duplicate permute->einsum patterns collapse into the same fused node first, and before DeadNodeElimination so the now-dead survivors of a redirect are swept.
Example (C++)
cg::Graph graph("cse"); { cg::CaptureGuard const capture(graph); cg::einsum("ij <- ik ; kj", 0.0, &C, 1.0, A, B); // C = A·B cg::einsum("ij <- ik ; kj", 0.0, &D, 1.0, A, B); // D = A·B -- identical subexpression cg::einsum("ij <- ij ; ij", 0.0, &E, 1.0, C, D); // reads both } cg::PassManager pm; pm.add<cg::passes::CSE>(); graph.apply(pm); // or PassManager::create_default() // The second einsum is gone; E now reads C for both operands.Example (Python)
import einsums, einsums.graph as cg g = cg.Graph("cse") with cg.capture(g): einsums.einsum("ij <- ik ; kj", C, A, B) # C = A·B einsums.einsum("ij <- ik ; kj", D, A, B) # D = A·B -- duplicate cse = cg.CSE() pm = cg.PassManager(); pm.add(cse) g.apply(pm) # or cg.default_pass_manager() # cse.num_eliminated -> 1 (the duplicate node is removed from g)
Limitations
Only pure-overwrite producers are eligible: einsum with c_prefactor == 0, axpby / permute / batched-gemm with beta == 0. Accumulating ops (nonzero destination prefactor) and scale/axpy/element-transform (whose scalar coefficients are not carried in op_data, so equality can’t be decided) are never merged.
A node of a descriptor registered outside the library is merged only when its codec’s equal hook calls the two the same, its destination hook says it overwrites all of what it writes, and it is deterministic without external effects; and only exactly, never proportionally (DescriptorHooks.hpp).
The duplicate’s outputs must be graph-owned intermediates that are not views (is_intermediate && aliases == 0); a user-visible output is left in place because the user reads that tensor directly, not through an executor slot. A node that writes a view is never a candidate at all.
Every reader of the duplicate’s output must name the output itself. Graph::redirect_slot repoints the duplicate’s own slot, so a reader reaching the same storage through a view of it, or through a slot redirected onto it, is left reading a buffer no node writes any more.
Every merged output buffer must have exactly one writer in the whole graph (Guard B), and the shared inputs must not be overwritten by any node between the two candidates (Guard A); either condition would make the reused value stale.
Neither output may be a buffer a control-flow node’s sub-graph reads or writes (Guard D). A Loop/Conditional node’s own inputs/outputs do not list what its body touches (that is
Graph::effective_io), and redirect_slot repoints only this graph’s slot table, so a body reading the eliminated duplicate’s output would read a never-written buffer.Neither output may be visible outside the graph being rewritten (Guard F). Graph::redirect_slot repoints only that graph’s slot table, so a reader in the parent, a sibling branch, or a nested body would keep reading the eliminated duplicate’s now never-written buffer. Inside a sub-graph the SURVIVOR must additionally be graph-owned: a loop predicate or DIIS callback runs between iterations and can write user tensors from Python, which no node list describes.
The paired outputs must hold the same element types (Guard G). Equal op_data and inputs do not imply it once operands may differ in type: f <- d*d and d <- d*d over the same operands differ only in C.
A proportional (r != 1) merge additionally needs EVERY reader of the duplicate’s output to absorb r (Guard E): an einsum or axpby reading it as exactly one operand through live shared params. permute and batched-gemm bake their scalars into the executor closure, so a reader of either blocks the merge.
Matching walks the node list once, bucketing candidates by (kind, redirected inputs, output count) and comparing each node only against earlier survivors in its own bucket. The bucket key deliberately excludes op_data, so two nodes differing only in a prefactor still meet.
Future improvements
Fold user-visible duplicates, and proportional duplicates whose readers cannot absorb the factor, behind an inserted scaled copy of the survivor. A copy is two sweeps over the result while an outer product is barely more than one, so this needs a cost model to decide (CostModel’s permute/bandwidth estimate, roadmap 3.3) rather than always being a win.
Recursing into sub-graphs is DONE: run() walks the tree itself. The SCF-body case that originally motivated the opt-out (axpby(1,H,0,F) and axpby(1,H,0,sum_HF) diverging afterwards) turns out to be ruled out by Guard B already, since both destinations are written twice.
- num_eliminated: int#
How many duplicate nodes the last
runeliminated, across the whole tree.Every other structural-algebraic pass carries one of these, and this pass wanting one is not symmetry: a differential test that runs a single pass over a corpus and finds no difference has proved the pass is faithful OR that it never fired, and without a count it cannot tell those apart. Reset at the top of
run.(read-only)
- class einsums.graph.CaptureContext#
Thread-local capture context for recording operations into a graph.
The CaptureContext manages the state machine for graph capture. When capturing is active, the graph-aware operation wrappers (einsums::compute_graph::einsum, etc.) call record() to add nodes to the graph instead of executing operations directly.
Each thread has its own CaptureContext (thread-local singleton), so capture is thread-safe. Nested captures are not supported.
Users typically don’t interact with CaptureContext directly, use CaptureGuard instead for RAII-based capture.
See also
CaptureGuard for the RAII wrapper
See also
Graph for the container that receives captured nodes
- static current() CaptureContext#
Access the thread-local CaptureContext singleton.
- Returns:
Reference to this thread’s CaptureContext.
- begin_capture(graph: Graph) None#
Start capturing operations into the given graph.
All subsequent calls to graph-aware operation wrappers on this thread will record nodes into the graph instead of executing.
- Parameters:
graph – The graph to capture into.
- Raises:
Exception – If already capturing (nested captures not supported).
- class einsums.graph.ConstantFolding#
Constant folding: evaluates nodes whose inputs never change once, at pass time, and replaces them with no-ops.
A node is foldable when every input tensor is “constant” – no node in the graph writes it – and the node is not a control- flow / memory / I/O / communication / user-defined kind. Folding is transitive: once a node is folded its outputs become constant too, so a chain of setup ops (building transformation, orthogonalization, or denominator matrices from fixed data) collapses in one topological sweep. The folded node is executed immediately and its executor replaced with a no-op, so the result is baked and skipped on every graph.execute().
Only graph-owned intermediates (create_tensor()) never written by any node are seeded as constant. User-owned tensors are NOT assumed constant – they may change between loop iterations or successive execute() calls – which keeps the pass safe for both one-shot graphs and loop bodies.
In the default pipeline (populate_default, first pass; also the head of the O1 cleanup cluster in PassManager::create_for).
Example (C++)
cg::Graph graph("constant_folding"); { cg::CaptureGuard const capture(graph); // A and B are graph-owned intermediates filled before capture and never written here. cg::einsum("ij <- ik ; kj", 0.0, &S, 1.0, A, B); // constant -> evaluated once, becomes a no-op cg::scale(2.0, &S); // reads S; after folding S is constant, so this folds too } cg::PassManager pm; pm.add<cg::passes::ConstantFolding>(); graph.apply(pm); // or PassManager::create_default() // Both nodes are no-ops after the pass; S holds its final value and replays for free.Example (Python)
import einsums, einsums.graph as cg g = cg.Graph("constant_folding") # A and B are graph-owned intermediates, populated then never written in capture. with cg.capture(g): einsums.einsum("ij <- ik ; kj", S, A, B) # constant -> folded einsums.linalg.scale(2.0, S) # folds transitively cf = cg.ConstantFolding() pm = cg.PassManager(); pm.add(cf) g.apply(pm) # or cg.default_pass_manager() # cf.num_folded -> 2 (getter is a property, not a method)
Limitations
Constants are seeded only from graph-owned intermediates never written by a node; user-owned inputs are never treated as constant, so a graph fed entirely from user tensors folds nothing.
A node is folded only when all of its tensors are already Materialized at pass time. ConstantFolding runs before the Materialization pass, so deferred (shell) tensors – notably loop-body workspace – are skipped rather than executed against unallocated storage.
Never folds control-flow (Conditional, Loop), memory (Alloc, Free, Materialize, Initialize), I/O (DiskRead, DiskWrite), GPU transfer (HostToDevice, DeviceToHost), collective (Allreduce, Broadcast, Allgather, Scatter, Barrier), or Custom nodes.
Folding has a side effect: it mutates tensor data during the pass, not at execute() time.
Future improvements
A second constant-folding phase after Materialization could fold chains whose intermediates are deferred until then and are currently skipped by the materialization guard.
- class einsums.graph.ContractionPlanning#
Multi-objective contraction planning pass.
Detects chains of GEMM-pattern einsum nodes and computes the optimal contraction order using a cost model that considers:
FLOPs (compute time scaled by shape-dependent GEMM efficiency)
Memory traffic (read/write bandwidth to main memory)
Kernel overhead (BLAS call and allocation costs)
GEMM shape efficiency (small/skinny GEMMs are slower per FLOP)
This pass actually restructures the graph: it declares deferred intermediate tensors and rewrites the contraction sequence (via a standard matrix-chain DP over the chain’s leaf matrices) to minimize estimated wall-clock time.
The cost model uses a CostModel that can be auto-detected, loaded from a JSON calibration file, or provided programmatically.
In the default pipeline (planning phase, before GEMMBatching / Reorder and before DistributionPlanning / Materialization, which size and allocate the deferred intermediates it introduces; create_default passes the shared CostModel).
Example (C++)
cg::Graph graph("contraction_planning"); { cg::CaptureGuard const capture(graph); // A chain whose left-to-right order is not the cheapest parenthesization. // T is a graph-owned intermediate consumed only by the second GEMM. cg::einsum("il <- ik ; kl", 0.0, &T, 1.0, A, B); // T = A * B cg::einsum("in <- il ; ln", 0.0, &D, 1.0, T, C); // D = (A*B) * C } graph.apply(cg::PassManager::create_default()); // ContractionPlanning runs here // If (A*(B*C)) is cheaper, the chain is re-parenthesized and T's write is // replaced by a fresh deferred intermediate.Example (Python)
import einsums, einsums.graph as cg g = cg.Graph("contraction_planning") with cg.capture(g): einsums.einsum("il <- ik ; kl", T, A, B) # T = A * B einsums.einsum("in <- il ; ln", D, T, C) # D = (A*B) * C g.apply(cg.default_pass_manager()) # ContractionPlanning runs in the default pipeline # Standalone, it prices against the detected machine, or by flops alone: pm = cg.PassManager() pm.add(cg.ContractionPlanning(cg.ChainPricing.Flops))
Limitations
Restructures only chains of pure contractions: each member must have c_prefactor == 0, at least one link index, exactly one output and two inputs, and each output must feed exactly one operand of the next member.
A chain must have >= 2 members and an estimated speedup > 1.05x; otherwise it gets a cost report only (analysis, no rewrite).
Only rank-2 shaped chains are restructured; a higher-rank operand would need its outer dimensions flattened, which this pass does not do. Rank-2 runtime-rank tensors are fine: the emitted executor reaches each operand through its impl and the dynamic-rank gemm overload, so there is no Tensor<T,2>* cast to be confused by.
Leaf orientation is carried as a transpose flag on the emitted GEMM, so a chain captured with transposed operands (ik;jk->ij) folds like any other and no permute is inserted. What still cannot be expressed: a member whose OUTPUT is permuted (ji <- ik ; kj) - there is no flag that writes an M x N result as N x M - an operand whose link indices are interleaved with its targets (no flat (M,K) reading at all), and a chain where the running product enters a later member as input_b (the matrix-chain DP assumes left-to-right leaf order, and GEMM does not commute).
A squaring node (OUT = T*T) breaks the chain (T would be both link and leaf), and unknown dtypes are analysis-only.
Interior outputs of the chain must be graph-owned, unaliased intermediates read by no node outside the chain; a user-visible or externally-read interior value makes the eliminated write observable, so the chain is declined.
The chain’s final output must not share a buffer with any leaf. The original order reads an early member’s leaves before the last member writes, and a re-parenthesized tree can read one of them in the GEMM that writes, as in A = (A*B)*L. Views of one parent share a buffer even where their elements are disjoint, so such a chain is declined too.
Leaves and the final output may be views: the emitted GEMM reads every operand through its impl and its strides, and falls back to a strided loop when an operand has no BLAS reading.
Future improvements
Flatten higher-rank operands into a rank-2 (M,K) reading so those chains restructure too.
Insert a permute for an operand whose link indices are interleaved with its targets, priced against the saving with
DeviceProfile::estimate_permute_time_us. Only reachable above rank 2, so it is blocked behind the flattening above.Reorder the leaf list when the running product enters a member as input_b, instead of declining the chain.
- __init__() None#
- __init__(pricing: ChainPricing) None
Construct with auto-detected hardware cost_model.
- class einsums.graph.CrossSpaceFinding#
One index letter of one contraction binding two different index spaces.
A value type, so a caller may keep it after the pass and the graph are gone. The two sides are named “first” and “second” in operand order (A before B before C), and the message repeats everything the fields carry so a report needs nothing else.
- severity: CrossSpaceSeverity#
How much to worry.
- class einsums.graph.CrossSpaceValidation#
Flag contraction letters that bind one operand’s slot against a slot of another space.
The bug this exists to catch is a letter binding an
occslot of one operand against avirtslot of another. In a coupled-cluster transcription that is almost always a mistake, and it is one the differential fuzzers cannot catch, because a hand-derived reference and its implementation are self-consistently wrong together.What capture already catches, and why this pass is still needed
Capture raises when a letter binds two different DECLARED spaces within one contraction, so a program annotated before it is captured is already policed. This pass covers everything capture cannot see:
annotations that arrive AFTER capture, through
Graph::annotate_spaces, which capture never revisits,annotations
SpacePropagationinferred, which that pass declines to argue about by design and leaves for diagnosis here,relation-aware verdicts. Capture asks only whether two ids are equal. This pass asks the registry whether the two spaces are disjoint, whether one contains the other, or whether nothing declared relates them, and reports three different things.
The verdicts
A letter is re-derived from the operands’ CURRENT handle annotations, never from the map frozen into the node at capture, and each slot binding it is compared against the first:
Same space: nothing to report.
Declared DISJOINT: an error. The contraction as written sums over an empty intersection, so it is identically zero, which is essentially never what the author meant.
One CONTAINED in the other: a note. Contracting a
pnoslot against avirtslot is a restriction of the parent space to a subspace, which the design’s containment reasoning treats as legitimate. Listed because a restriction that was not intended looks exactly like one that was.Nothing declared either way: a warning. The registry holds only what was declared, and “unknown” is a first-class answer that must be treated as carefully as “no”.
A finding involving a slot whose annotation was INFERRED is reported one level lower and says so. An inference is a derivation from someone else’s declaration, and an authoritative verdict resting on a derived premise is worse than a weak verdict resting on a firm one.
The pass never fails a pipeline
It never throws, never mutates, and
runalways reports “not modified”. A diagnosis is delivered throughfindings,explainandprint_report, and what to do about it is the caller’s decision.Example (C++)
graph.annotate_spaces(A, {occ, virt}); graph.annotate_spaces(B, {occ, aux}); // 'a' meets virt on A and occ on B auto [modified, check] = graph.apply<cg::passes::CrossSpaceValidation>(); for (auto const &finding : check.findings()) { std::cerr << finding.message << '\n'; }Example (Python)
check = cg.CrossSpaceValidation() pm = cg.PassManager() pm.add(check) pm.run(g) for finding in check.findings: print(finding.severity, finding.message) print(check.report_string())
Limitations
Contraction nodes only. Every other kind is counted in
skip_reasons; a linear combination whose operands disagree slot by slot is a real cross-space bug and is not yet reported here.One finding per pair of distinct spaces on one letter, compared against the letter’s first binding, so a letter binding three spaces yields two findings rather than three.
An unannotated program yields nothing, which is the honest answer: with no premises the registry can prove nothing. The way to make the pass useful is to annotate.
The verdicts read only DECLARED relations. Two spaces that genuinely never overlap but were never declared disjoint produce a warning, not an error.
Future improvements
Cover
Axpbyand the element-wise kinds, whose operands must agree slot by slot.An option to promote errors to an exception, for a build that wants a wrong transcription to stop the run rather than to be reported.
- report_string() str#
The same report
print_reportwrites, returned as a string.The form a caller that is not holding a stream wants, which is every Python caller and every test that asserts on what the report says. Streams are not bound, and a returned string needs no flushing to be readable.
- Returns:
The report, most severe finding first. Empty for a clean or an unannotated graph.
- findings: list[CrossSpaceFinding]#
Every finding, in the order the nodes were visited and letters sorted within a node.
(read-only)
- class einsums.graph.DataflowExecutor#
TaskPool dataflow executor, maximum overlap via continuations.
Uses the TaskPool module to execute graph nodes as dataflow tasks. Each node is submitted when all its predecessors complete, using TaskHandle continuations for zero-barrier scheduling.
Independent nodes run concurrently across TaskPool workers. The work-stealing deque provides automatic load balancing.
Note
Requires the TaskPool module. Falls back to SequentialExecutor if TaskPool is not available.
Example
cg::DataflowExecutor df_exec; graph.execute(df_exec); // Maximum overlap via TaskPool
- set_memory_budget(bytes: int) None#
Set a memory budget for execution.
When set (> 0), the executor tracks live tensor memory and gates Materialize node submissions to stay within the budget. Free nodes release memory and wake blocked submissions.
- Parameters:
bytes – Maximum bytes of simultaneously live tensor data. 0 = unlimited (default).
- class einsums.graph.DeadNodeElimination#
Dead node elimination (DNE): removes producers whose every output is an unread graph-owned intermediate.
A node is dead when ALL of its outputs are graph-owned intermediates (is_intermediate == true) that are not read by any node in this graph, not referenced by any descendant sub-graph (a nested loop body / conditional branch), and not referenced by any enclosing or sibling graph. Output tensors owned by the user are always considered live – user code may read them directly – so only unread intermediates are candidates. Outputs are resolved through view aliases to their owning buffer, so a write through a view of a live tensor keeps its producer.
Especially useful after CSE (or any pass that redirects consumers away from a node), which can strand a now-unread producer.
In the default pipeline (populate_default; also the O1 cleanup cluster in PassManager::create_for). Runs right after CSE.
Example (C++)
cg::Graph graph("dne"); { cg::CaptureGuard const capture(graph); auto &Tmp = graph.create_tensor<double, 2>("Tmp", m, n); // graph-owned intermediate cg::einsum("ij <- ik ; kj", 0.0, &Tmp, 1.0, A, B); // writes Tmp -- but nothing reads it cg::einsum("ij <- ik ; kj", 0.0, &C, 1.0, A, B); // C is the real (user-visible) result } cg::PassManager pm; pm.add<cg::passes::DeadNodeElimination>(); graph.apply(pm); // or PassManager::create_default() // The Tmp-producing einsum is removed; the C-producing einsum stays.Example (Python)
import einsums, einsums.graph as cg g = cg.Graph("dne") tmp = g.create_tensor("Tmp", [m, n], dtype="float64") # graph-owned intermediate, never read with cg.capture(g): einsums.einsum("ij <- ik ; kj", tmp, A, B) # dead: nothing consumes tmp einsums.einsum("ij <- ik ; kj", C, A, B) # live dne = cg.DeadNodeElimination() pm = cg.PassManager(); pm.add(dne) g.apply(pm) # or cg.default_pass_manager() # dne.num_eliminated -> 1 (getter is a property, not a method)
Limitations
Only graph-owned intermediates are ever removed. A dead write into a user-owned tensor is kept, because the user may read that storage after execute().
Control-flow nodes (Conditional, Loop) and memory nodes (Alloc, Free) are never eliminated, nor is a side-effect-only node that has no outputs (e.g. an in-place scale).
A node with external effects (
NodeEffects; acg::customclosure not declared pure) is kept whatever becomes of its outputs.Liveness is a reachability analysis: it removes a producer whose result nothing reads, but does not prune a live-but- redundant computation, nor perform partial-output DCE (a node is kept whole if any one output is live).
Cross-graph liveness is threaded manually: recurse_into_subgraphs() == false and run() descends the sub-graph tree itself, passing each child the set of buffers referenced by its parent and every sibling sub-tree (a per-graph recursion would wrongly kill a body producer whose only reader sits in the parent after the loop or in a sibling body).
Future improvements
Partial-output elimination: rewrite a surviving node to stop producing its individually-dead outputs, rather than keeping the whole node whenever a single output is live.
- pruned_tensors: list[str]#
The graph-owned tensors whose only writer this pass removed.
Every entry is a tensor nothing in the graph reads, which is exactly the case the pass exists to remove. It is ALSO exactly what a caller sees who created a result with the scratch-defaulted creator and reads it after
execute(): the answer is pruned and the buffer keeps whatever it held. The two are indistinguishable from inside the graph, so rather than guess, the pass names what it dropped andexplainsays what to do about it. Without this the case reports only as a node count, which is what made it a bisect.(read-only)
- class einsums.graph.Decision#
One thing a pass did, declined or said, as a record.
What
OptimizerPass::explainandOptimizerPass::skip_reasonsprint is rendered from these; a program reads the fields instead. A record from a call a pass has not yet given aReasonhas an emptycodeand carries its words inreasonandtext.Added in version 2.0.0.
- fact(name: str) float#
The value of the fact named
name.- Parameters:
name – The fact’s name.
- Returns:
Its value, or 0 when the decision carries no such fact.
- kind: DecisionKind#
- class einsums.graph.DeltaElimination#
Eliminate contractions against a tagged Kronecker delta by index substitution.
The first real client of the region rewrite framework: unlike
RegionIdentityit changes the statement list, and unlike a peephole it decides what to do with the result by asking the escape analysis whether the delta contraction’s output can be dissolved.
- class einsums.graph.DiisAcceleratorF#
Pulay DIIS extrapolation over a set of (amplitude, step) tensor pairs.
Accelerates the
t <- t + stepupdate a fixed-point iteration performs by keeping a short history of (amplitude, step) snapshots and replacing the amplitudes with the least-squares extrapolant. The error vector is the update step itself, the standard coupled-cluster choice, so an iteration whose step the body computes anyway gets DIIS for the cost of a K-sized host-side solve.One
stepcall does the whole update: the snapshot copies, the one new row of the B matrix, the normalized bordered solve, and the extrapolation. The amplitudes update IN PLACE, so pointers a graph captured stay valid; the B entries are conjugated inner products, so complex dtypes are exact and the coefficients are real; and the (K+1)-sized system solves withgesv.Why the interior is BLAS and memcpy rather than tensor operations
A DLPNO-(T) step is near ten thousand operations on operands of a few thousand elements, where the eager layer’s per-call overhead (profiling, shape checks, dispatch) costs more than the arithmetic. So contiguous operands go straight to the same BLAS calls the eager layer would reach (
scal+axpy,dot/dotc), keeping results bitwise identical; a strided view keeps the eager path.The B entries are CACHED across steps, keyed by snapshot identity: a step adds one snapshot, so only one row is new. Each entry sums its components in registration order, one
dotper component, which is what the cross-implementation bit-identity gate rests on: one dot over the concatenated components would reduce in a different order. The per-solve copy of B is normalized by its largest element before the solve, and a singular B drops the oldest history pair and retries.Operand binding
add_pairbinds to the storage the operand holds AT THAT MOMENT, the way a view does. Rebinding or resizing an amplitude or a step tensor afterwards leaves the accelerator reading the old buffer; the caller must add pairs whose storage outlives the accelerator. Adding a pair once a history exists is rejected, because the existing snapshots are shaped for the old pair list.- __init__(k: int = 8) None#
A history of at least 2 is required: one snapshot has nothing to extrapolate between.
- step() None#
Push the current (amplitudes, steps) onto the history and extrapolate the amplitudes in place.
- reset() None#
Forget every snapshot, keeping the registered pairs. The next step starts the history over.
- class einsums.graph.DiisAcceleratorD#
Pulay DIIS extrapolation over a set of (amplitude, step) tensor pairs.
Accelerates the
t <- t + stepupdate a fixed-point iteration performs by keeping a short history of (amplitude, step) snapshots and replacing the amplitudes with the least-squares extrapolant. The error vector is the update step itself, the standard coupled-cluster choice, so an iteration whose step the body computes anyway gets DIIS for the cost of a K-sized host-side solve.One
stepcall does the whole update: the snapshot copies, the one new row of the B matrix, the normalized bordered solve, and the extrapolation. The amplitudes update IN PLACE, so pointers a graph captured stay valid; the B entries are conjugated inner products, so complex dtypes are exact and the coefficients are real; and the (K+1)-sized system solves withgesv.Why the interior is BLAS and memcpy rather than tensor operations
A DLPNO-(T) step is near ten thousand operations on operands of a few thousand elements, where the eager layer’s per-call overhead (profiling, shape checks, dispatch) costs more than the arithmetic. So contiguous operands go straight to the same BLAS calls the eager layer would reach (
scal+axpy,dot/dotc), keeping results bitwise identical; a strided view keeps the eager path.The B entries are CACHED across steps, keyed by snapshot identity: a step adds one snapshot, so only one row is new. Each entry sums its components in registration order, one
dotper component, which is what the cross-implementation bit-identity gate rests on: one dot over the concatenated components would reduce in a different order. The per-solve copy of B is normalized by its largest element before the solve, and a singular B drops the oldest history pair and retries.Operand binding
add_pairbinds to the storage the operand holds AT THAT MOMENT, the way a view does. Rebinding or resizing an amplitude or a step tensor afterwards leaves the accelerator reading the old buffer; the caller must add pairs whose storage outlives the accelerator. Adding a pair once a history exists is rejected, because the existing snapshots are shaped for the old pair list.- __init__(k: int = 8) None#
A history of at least 2 is required: one snapshot has nothing to extrapolate between.
- step() None#
Push the current (amplitudes, steps) onto the history and extrapolate the amplitudes in place.
- reset() None#
Forget every snapshot, keeping the registered pairs. The next step starts the history over.
- class einsums.graph.DiisAcceleratorC#
Pulay DIIS extrapolation over a set of (amplitude, step) tensor pairs.
Accelerates the
t <- t + stepupdate a fixed-point iteration performs by keeping a short history of (amplitude, step) snapshots and replacing the amplitudes with the least-squares extrapolant. The error vector is the update step itself, the standard coupled-cluster choice, so an iteration whose step the body computes anyway gets DIIS for the cost of a K-sized host-side solve.One
stepcall does the whole update: the snapshot copies, the one new row of the B matrix, the normalized bordered solve, and the extrapolation. The amplitudes update IN PLACE, so pointers a graph captured stay valid; the B entries are conjugated inner products, so complex dtypes are exact and the coefficients are real; and the (K+1)-sized system solves withgesv.Why the interior is BLAS and memcpy rather than tensor operations
A DLPNO-(T) step is near ten thousand operations on operands of a few thousand elements, where the eager layer’s per-call overhead (profiling, shape checks, dispatch) costs more than the arithmetic. So contiguous operands go straight to the same BLAS calls the eager layer would reach (
scal+axpy,dot/dotc), keeping results bitwise identical; a strided view keeps the eager path.The B entries are CACHED across steps, keyed by snapshot identity: a step adds one snapshot, so only one row is new. Each entry sums its components in registration order, one
dotper component, which is what the cross-implementation bit-identity gate rests on: one dot over the concatenated components would reduce in a different order. The per-solve copy of B is normalized by its largest element before the solve, and a singular B drops the oldest history pair and retries.Operand binding
add_pairbinds to the storage the operand holds AT THAT MOMENT, the way a view does. Rebinding or resizing an amplitude or a step tensor afterwards leaves the accelerator reading the old buffer; the caller must add pairs whose storage outlives the accelerator. Adding a pair once a history exists is rejected, because the existing snapshots are shaped for the old pair list.- __init__(k: int = 8) None#
A history of at least 2 is required: one snapshot has nothing to extrapolate between.
- step() None#
Push the current (amplitudes, steps) onto the history and extrapolate the amplitudes in place.
- reset() None#
Forget every snapshot, keeping the registered pairs. The next step starts the history over.
- class einsums.graph.DiisAcceleratorZ#
Pulay DIIS extrapolation over a set of (amplitude, step) tensor pairs.
Accelerates the
t <- t + stepupdate a fixed-point iteration performs by keeping a short history of (amplitude, step) snapshots and replacing the amplitudes with the least-squares extrapolant. The error vector is the update step itself, the standard coupled-cluster choice, so an iteration whose step the body computes anyway gets DIIS for the cost of a K-sized host-side solve.One
stepcall does the whole update: the snapshot copies, the one new row of the B matrix, the normalized bordered solve, and the extrapolation. The amplitudes update IN PLACE, so pointers a graph captured stay valid; the B entries are conjugated inner products, so complex dtypes are exact and the coefficients are real; and the (K+1)-sized system solves withgesv.Why the interior is BLAS and memcpy rather than tensor operations
A DLPNO-(T) step is near ten thousand operations on operands of a few thousand elements, where the eager layer’s per-call overhead (profiling, shape checks, dispatch) costs more than the arithmetic. So contiguous operands go straight to the same BLAS calls the eager layer would reach (
scal+axpy,dot/dotc), keeping results bitwise identical; a strided view keeps the eager path.The B entries are CACHED across steps, keyed by snapshot identity: a step adds one snapshot, so only one row is new. Each entry sums its components in registration order, one
dotper component, which is what the cross-implementation bit-identity gate rests on: one dot over the concatenated components would reduce in a different order. The per-solve copy of B is normalized by its largest element before the solve, and a singular B drops the oldest history pair and retries.Operand binding
add_pairbinds to the storage the operand holds AT THAT MOMENT, the way a view does. Rebinding or resizing an amplitude or a step tensor afterwards leaves the accelerator reading the old buffer; the caller must add pairs whose storage outlives the accelerator. Adding a pair once a history exists is rejected, because the existing snapshots are shaped for the old pair list.- __init__(k: int = 8) None#
A history of at least 2 is required: one snapshot has nothing to extrapolate between.
- step() None#
Push the current (amplitudes, steps) onto the history and extrapolate the amplitudes in place.
- reset() None#
Forget every snapshot, keeping the registered pairs. The next step starts the history over.
- class einsums.graph.DistributiveFactoring#
Distributive factoring pass: factors out shared operands from accumulating einsums.
Detects groups of einsum nodes that:
Accumulate into the same output tensor (c_prefactor != 0)
Share one input operand with identical index pattern
Have different other operands with identical index pattern and shape
Rewrites by summing the non-shared operands into an intermediate, then performing a single einsum with the shared operand and the sum.
The lowering is ordinary nodes, not one fused node: a Scale that zeros the intermediate, one Axpy per summed operand carrying that member’s product prefactor, and one Einsum with
ab_pf = 1, so other passes can share or hoist the intermediate.Groups that sum the same operands, up to an overall factor, share one intermediate, so a quantity several terms consume is built once. This is the shape of CCSD’s tau, which feeds W_mnij and W_abef with a quarter and the T2 equation with a half: written out term by term, with no hint that tau exists, the pass recovers it, builds it once, and puts each consumer’s factor on that consumer’s contraction. Reuse lives here rather than in CSE because an accumulation buffer has several writers, and CSE’s single-writer guard is what stops readers being redirected onto a buffer that is mutated again.
Example (CCSD-like pattern)
Before:
// R[i,a] += A[i,k] * B1[k,a] (einsum node 1) // R[i,a] += A[i,k] * B2[k,a] (einsum node 2) // R[i,a] += A[i,k] * B3[k,a] (einsum node 3)
After:
// T[k,a] = 0 (Scale by zero) // T[k,a] += B1[k,a] (Axpy) // T[k,a] += B2[k,a] (Axpy) // T[k,a] += B3[k,a] (Axpy) // R[i,a] += A[i,k] * T[k,a] (single Einsum)
This reduces N contractions to 1 contraction + (N-1) additions, saving significant FLOPs when the contraction is expensive relative to the addition.
Profitability
Priced, not guessed. The trade is (N-1) contractions saved against one axpy chain over the summed operands plus a buffer, so it pays when the contraction is flop-bound and loses when it is bandwidth-bound: a cheap contraction over large operands spends more assembling the sum than it saves, and pays memory for the privilege. Both sides are estimated in microseconds from the shared
CostModel, the same way TiledExpansion chooses between its lowerings, andnum_unprofitablecounts the groups declined on those grounds.Note the direction of the memory effect: factoring ADDS a buffer that the unfactored form does not need. Sharing reduces how many it adds when several consumers want one sum; it does not make the pass a memory saving.
In the default pipeline
Registered by
PassManager::populate_default(), next toLinearCombinationContractionFoldingand beforeLoopInvariantHoisting, so a loop-invariant sum is built once rather than every replay. Because it self-gates on cost, it is a no-op on graphs it cannot help. To exercise it alone, or to price it against a chosen profile:auto [modified, pass] = graph.apply<cg::passes::DistributiveFactoring>(); auto [modified, pass] = graph.apply<cg::passes::DistributiveFactoring>(my_cost_model);
Example (Python)
import einsums, einsums.graph as cg g = cg.Graph("distributive_factoring") with cg.capture(g): einsums.einsum("ia <- ik ; ka", R, A, B1, c_pf=1.0) # R += A * B1 einsums.einsum("ia <- ik ; ka", R, A, B2, c_pf=1.0) # R += A * B2 df = cg.DistributiveFactoring() pm = cg.PassManager(); pm.add(df) g.apply(pm) # df.num_groups -> 1, df.num_eliminated -> 1 (getters are properties, not methods)
Limitations
Members must be einsum nodes with exactly two inputs and one output, accumulating (c_prefactor != 0) into the same output, sharing one operand (same tensor id and index pattern) with the non-shared operands sharing the other index pattern.
Every member after the first must accumulate with c_prefactor == 1. The combined contraction applies the output prefactor once, so a member that rescales the partial sum its predecessors wrote cannot be folded: R = 2*(R + A*B1) + A*B2 is not R = 2*R + A*(B1 + B2). Such a group declines rather than silently computing the second form.
Sharing covers sums that are equal or PROPORTIONAL: a consumer wanting the same sum at a different strength reuses the build and carries the ratio on its own
ab_pf, which is free. The ratio must be an exact power of two, because only then does scaling the assembled sum agree with scaling each term (r*(a+b) == r*a + r*b). Other ratios decline; lifting that is safe up to rounding but would make the answer depend on what the pass chose to share.Sums that are not proportional stay separate even when related. CCSD’s tau and tau-tilde are
T2 + PandT2 + P/2for the sameP, a ratio of 1 on one term and 1/2 on the others, so they are two tensors here. That matches practice: deriving one from the other saves a single pass over an o^2v^2 buffer against contractions costing o^2v^4, and serialises two builds that are otherwise independent. Seeing them as one quantity at two coefficients is multi-term optimisation over a coefficient matrix, which nothing here does.Reuse only looks within one graph level. A sum built in a loop body is not offered to the enclosing graph or to a sibling branch.
Non-shared operands must all be distinct tensors of identical shape and dtype, and the shared operand may not be one of them.
The factoring math is real-valued: conj_a/conj_b einsums are skipped, and a prefactor with a nonzero imaginary part declines the node.
Operands may be runtime tensors, typed Tensor<T, Rank> or views of either, mixed freely: the summed intermediate is a runtime tensor, and every rebuilt node reads its operands through their rank-erased geometry. The output may not be a view.
Placement/interference gate: the combined node takes the first member’s slot, so no node between the first and last member may read/write the output or write a factor operand, and any Loop/Conditional in the span disqualifies the group.
Future improvements
Thread conj_a/conj_b and complex prefactors through the rewrite so conjugated / complex-scaled contractions can also be factored.
Fold the zeroing Scale into the first Axpy once an Axpby node factory exists, saving a node per group.
Offer sums across graph levels, so a loop-invariant one built in a CC iteration can be shared with, or hoisted above, the enclosing graph.
- __init__() None#
- __init__(factor: Factor) None
Override the profitability decision.
Factor::Alwaysskips it entirely.
- class einsums.graph.ElementWiseFusion#
Element-wise operation fusion: collapses directly consecutive Scale or axpby ops on the same tensor into a single node.
In the default pipeline (populate_default; also the O1 cleanup cluster in PassManager::create_for). Runs after SymmetrizedAccumulation, which must fold its r2 += s*(tmp + P(tmp)) idiom before this pass merges the two axpby and hides the pattern.
Example (C++)
cg::Graph graph("elementwise_fusion"); { cg::CaptureGuard const capture(graph); cg::scale(2.0, &C); // C *= 2 cg::scale(3.0, &C); // C *= 3 -- adjacent scale on the same tensor } cg::PassManager pm; pm.add<cg::passes::ElementWiseFusion>(); graph.apply(pm); // or PassManager::create_default() // One scale node remains with factor 6.Example (Python)
import einsums, einsums.graph as cg g = cg.Graph("elementwise_fusion") with cg.capture(g): einsums.linalg.scale(2.0, C) # C *= 2 einsums.linalg.scale(3.0, C) # C *= 3 ewf = cg.ElementWiseFusion() pm = cg.PassManager(); pm.add(ewf) g.apply(pm) # or cg.default_pass_manager() # ewf.num_fused -> 1 (getter is a property, not a method)
What it fuses
axpby chains: Y = a1·X + b1·Y directly followed by Y = a2·X + b2·Y on the same pair becomes Y = (a2 + b2·a1)·X + (b2·b1)·Y. axpby reads its scalars from live shared params, so this is a real fusion - the result is ONE sweep over Y. If the composed beta is zero the node stops listing Y as an input, since it no longer reads it.
Scale-into-Scale on the same tensor: the factors multiply. Also a real fusion - the composed factor is written to the scale’s live params and the merged node applies ONE multiply.
Limitations
Both fusions need live shared params on every participant, so a Scale or Axpby some pass assembled by hand without them is skipped rather than chained.
Both fusions need the participants to be DIRECTLY consecutive; the scan breaks on any intervening node, so ops separated by another node do not fuse even when nothing in between touches the tensor.
axpby fusion requires the same source X and the same destination Y. Two different sources are a three-operand update, which no single axpby expresses. It also requires all four prefactors to share a PrefactorScalar alternative.
axpby fusion also requires X and Y to occupy different buffers. Two views of one tensor are distinct ids, and when they overlap the first update changes the X the second one reads, which the composed scalars do not model. Disjoint views of one parent are declined with them.
ElementTransform is not composed: it holds an opaque callable, so two of them can only be chained, not merged.
Merged scalars are plain floating-point arithmetic; no reassociation or overflow handling.
- class einsums.graph.EventLog#
An observer that keeps every event, for reading after the replay: the way to observe a replay from Python, whose callbacks would serialize the executors on the GIL.
log = cg.EventLog() g.set_observer(log) g.execute() slowest = sorted((e for e in log.events if e.kind == cg.EventKind.NodeEnd), key=lambda e: e.ms)[-5:] log.write_chrome_trace("replay.json") # open in ui.perfetto.devAdded in version 2.0.0.
- write_chrome_trace(path: str) None#
Write the events as a Chrome trace: one track per thread, a span per node, an instant per storage event, readable in
ui.perfetto.devorchrome://tracing.- Parameters:
path – The file to write.
- Raises:
Exception – when the file cannot be written.
- events: list[ExecutionEvent]#
Every event so far, in the order they arrived.
(read-only)
- class einsums.graph.ExecutionEvent#
One thing that happened while a replay ran.
Every event carries the fields its kind has: a node event its node, a storage event its tensor, storage and bytes.
at_msis measured from the start of the outermost replay on one steady clock, so events from different threads order by it.Added in version 2.0.0.
- class einsums.graph.ExecutionObserver#
What hears a graph’s replays as they run, once attached with
Graph::set_observer.Events arrive on the thread they happen on: under the OpenMP and dataflow executors two calls can overlap, so an observer must be thread-safe. One that throws is detached and the failure logged once; the replay goes on. With no observer attached an executor tests one pointer per node.
Every member is inline, so a program can derive its own observer: an out-of-line one would keep the class’s vtable inside the library.
Added in version 2.0.0.
- class einsums.graph.Executor#
Abstract base class for graph execution backends.
An executor determines HOW graph nodes are executed, sequentially, in parallel via threads, on GPU streams, etc. The graph structure, optimization passes, and capture mechanism are executor-agnostic.
- class einsums.graph.Fact#
A named quantity a decision carries: a block size, a byte count, a run count.
Added in version 2.0.0.
- class einsums.graph.FactorizationPass#
Replace a tagged tensor by a provider’s factors, and re-associate around them.
The one pass every factorization method goes through. It finds a contraction with a tagged operand, asks each
FactorizationProviderclaiming that tag for a chain of factors, brackets the substituted product with the subset search, costs the bracketing against what was there, and takes the cheapest offer that is actually cheaper.What it does to one contraction
Given
C[c]=f*T[t]*O[o]withTtagged, and a provider sayingT[t]=A[a]*B[b]summed over the lettersaandbshare thattdoes not, the rewrite is:X[x] = B[b] * O[o] C[c] = f * A[a] * X[x]
with
xthe letters ofbandothataorcstill needs. Substituting alone would give a three-operand contraction, which has no node form and would be more arithmetic besides; the regrouping is the entire point, and DF’s saving is exactly this.A provider offering more than two factors gets the same treatment over a longer product. The leaves handed to the search are the provider’s factors and the other operand, every interior node of the chosen tree becomes a declared intermediate and a binary contraction, and the auxiliary letters are ordinary letters to the ranking.
More than one tagged leaf in one cone
The rule above is stated over the LEAF SET of the cone rather than over the two operands of a statement, and that is what lets several tagged tensors be replaced in one decision. A density-fitted four-external ladder never writes a contraction of two tagged operands: it writes a chain whose leaves are the three-index integral twice and the doubles amplitude once, so the tags land on the leaves the flattening exposes. Every such leaf is offered to its own providers, every combination of one plan per leaf is bracketed, and the cost of the whole doubly substituted cone is what decides. Neither fit pays alone there, which is the same shape the joint quadrature decision has: replacing the amplitude leaves the integral’s indices to be carried through and replacing the integral leaves the amplitude’s, and only both together collapse the contraction onto the grid letters.
Two fits in one cone must present the same index SPACES for the letters they introduce. Two grids chosen independently give a chain that carries both extents rather than contracting one away, so that is a decline with the reason rather than a rewrite that is quietly no better.
What it declines, and why each is a real case
A tagged tensor some node WRITES. Its factors would have to be refitted whenever it changed, and the setup body this pass emits runs once per bound problem. Only an operand nothing in the graph produces is safely factorizable this way.
A TWO-FACTOR split whose factors cannot be told apart by which one pairs with the other operand. The decomposition needs one factor carrying the letters shared with
Oand one not; if both do or neither does, there is no regrouping to make. Not asked of a longer chain, which has as many ways to meet the other operand as it has links and whose answer is the bracketing the search returns.A chain with more factors than the search is allowed. The subset program is exponential in the leaf count, and a cap is the honest way to bound it.
A decomposed form that is not symbolically cheaper. Substituting an approximation and getting slower is the worst of both, and the comparison is the total order of
SymbolicCostso the answer does not depend on iteration order.A cost the accuracy budget will not pay for, refused through
OptimizerPass::approximatewith the budget’s own reason.A tagged tensor no two-operand contraction reads at all. There is nothing to re-associate around, so the tag is reported unclaimed at the end of the run rather than passed over in silence: a tensor read only elementwise, or only through a dot, is the shape a caller tagging an integral in an energy expression most often writes.
Never in a default manager
A provider may be exact, but the pass is the lossy tier’s entry point and Part 5.1 says that tier is opt-in. It runs when a caller adds it, and only for tags a provider is registered for, so a process with no providers pays one lookup.
See also
Factorization.hpp for what a provider offers
- __init__() None#
- __init__(registry: FactorizationRegistry) None
Use the process-wide provider registry.
- set_laplace_transform(transform: LaplaceTransform) None#
Decide profitability jointly with this transform, and emit both rewrites together.
On canonical MP2 the tagged integral is read elementwise and never as a contraction operand, so this pass has no candidate at all; and until the integral is factored the transform’s numerator is a leaf and it has nothing to ride on. Neither can go first, and a veto taken on either alone refuses a rewrite that only the pair could make pay.
With a transform set, a tagged tensor multiplied by a tagged denominator becomes a candidate: the substituted product is emitted into an intermediate, the transform is applied to the TRIAL expression, and the cost of the pair is what decides. Both rewrites are then emitted together and both records land on the output.
The transform supplies its tolerance, its point override and its energy vectors, so it has to be handed the energies through
LaplaceTransform::add_energyexactly as it would be if it were running on its own. It does NOT need to be in the same pass manager; adding it there as well is harmless and reports the denominator as unclaimed, because this pass has already taken it.Note
Keeps the transform alive for as long as the pass, because a Python caller has no other reason to keep a reference to it.
- Parameters:
transform – The transform, or null to take every fit on its own merits.
- num_factorized: int#
How many contractions were re-associated around a provider’s factors.
(read-only)
- num_dissolved: int#
How many captured intermediates the cone flattening dissolved into a chosen tree.
Reported because it is the difference between re-associating one contraction and re-associating the cone it sits in, and a caller reading the node count would otherwise see a statement disappear with nothing saying which pass took it.
(read-only)
- num_multi_substituted: int#
How many rewrites substituted more than one tagged tensor at once.
The four-external ladder of a coupled-cluster iteration is the case: written in density- fitted form it is a chain whose leaves are the three-index integral twice and the doubles amplitude once, and it becomes a grid chain only when both are replaced by fits over ONE grid. Fitting either alone leaves the other’s indices to be carried through, which is a decline rather than a saving, so the two are one decision and this counts the times it was taken.
(read-only)
- num_joint: int#
How many rewrites were taken as one decision with a following quadrature.
(read-only)
- accept_rung: str#
Which rung of the symbolic comparison decided the last rewrite this pass took.
The chain is scale order, then typical extents, then bound extents, then a documented lexicographic tie-break that is arbitrary on purpose. “Symbolically cheaper” therefore says very different things depending on where it was settled, and a caller measuring a rewrite needs to know which: a verdict at the scale-order rung is the family argument, and one at the tie-break is the chain running out of ways to rank two polynomials.
(read-only)
- class einsums.graph.FactorizationProvider#
A way of rewriting one kind of tensor as a product of factors.
Register one instance per method. The pass asks every provider claiming a tensor’s provenance tag, costs each offer, and takes the cheapest that is actually cheaper.
Added in version 2.0.0.
- class einsums.graph.FactorizationRegistry#
The providers a process knows about.
Process-global by default, in the manner of
SpaceRegistry, because a provider is a capability of the build rather than of one graph. Registration is a startup act; a test that adds one is expected to remove it, andclearexists for exactly that.Added in version 2.0.0.
- add(provider: FactorizationProvider) None#
Register a provider.
- Parameters:
provider – The provider. Held by shared_ptr and must outlive nothing in particular: the registry owns a reference.
- Raises:
Exception – When a provider of the same name is already registered, naming it. Two providers under one name would make which of them ran depend on registration order, and a pass whose result depends on that is not reproducible.
- for_tag(tag: str) list[FactorizationProvider]#
Every provider claiming
tag, in registration order.- Parameters:
tag – A provenance tag name.
- Returns:
The providers. Empty when nothing claims it.
- claims(tag: str) bool#
Whether any provider claims
tag.- Parameters:
tag – A provenance tag name.
- Returns:
True when at least one does.
- class einsums.graph.GateFlags#
An array of conditional gates a graph reads without calling back into its caller.
Graph::add_conditionaltakes astd::function<bool()>, which is the general form and the right one when the answer has to be computed. It is the wrong one when the answer is already known before the replay starts and the graph holds hundreds of conditionals: a predicate bound to a Python callable takes the GIL on every evaluation, so a graph whose conditionals are executed from several threads serializes on it, and a caller that already knows every answer pays that serialization for nothing.This is the other form. The caller writes the whole array once per replay, through
fillorassign, and each conditional reads one slot of it. The buffer is shared: @ref Graph::add_conditional_flag bakes a copy of theshared_ptrinto the node at capture time, so the flags survive however long the graph does even if the handle the caller held is dropped first, and every node sees the same array on every replay. Evaluation is a load and a compare.The flags ride outside the dataflow and carry no ordering of their own, exactly as
LuPivotsdoes. Nothing serializes a write to a flag against a replay that reads it; the caller must finish writing before it callsexecute().cg::GateFlags live(blocks.size(), true); for (size_t b = 0; b < blocks.size(); b++) { auto [branch, _] = graph.add_conditional_flag(fmt::format("block [{}]", b), live, b); CaptureGuard const guard(branch); emit(blocks[b]); } live.set(3, false); // block 3 is skipped by the next replay graph.execute();- resize(count: int, value: bool = False) None#
Grow or shrink the array, giving any new flag
value.Resizing while a graph holds indices into the array is the caller’s problem: an index past the end reads false, which silently skips a branch rather than reading out of bounds.
- class einsums.graph.Graph#
A directed acyclic graph (DAG) of tensor operations.
The Graph class is the central container for the computation graph. It stores a sequence of operation nodes and the tensor handles they reference. Key features:
Capture: Operations are added during a capture phase (via CaptureGuard).
Topological sorting: Nodes are sorted based on data dependencies before execution.
Execution: All nodes execute in dependency order. Calling execute() multiple times replays the same operations (useful for iterative algorithms).
Optimization: Passes can be applied to fuse, eliminate, or reorder nodes.
Tensor ownership: Intermediate tensors can be created via create_tensor() so the graph manages their lifetimes.
Validation: Before execution, tensor pointers are checked for use-after-free.
Profiling: execute() wraps each node in profiler regions with annotations.
Visualization: print_dot() exports GraphViz format; print_summary() prints text.
namespace cg = einsums::compute_graph; auto A = create_random_tensor<double>("A", 10, 5); auto B = create_random_tensor<double>("B", 5, 8); cg::Graph graph("my_graph"); // declare_, not create_: C is a RESULT this code reads after execute(), so it must not be // marked scratch. create_zero_tensor would make it an intermediate, and DeadNodeElimination // removes the einsum below the moment the graph is optimized, leaving C as it was. auto &C = graph.declare_zero_tensor<double, 2>("C", 10, 8); { cg::CaptureGuard guard(graph); cg::einsum("ik;kj->ij", &C, A, B); } graph.optimize(); // also materializes C, whose allocation declare_ deferred graph.execute(); // C = A * B graph.execute(); // Replay: C = A * B againSee also
CaptureGuard for the RAII capture mechanism
See also
Pipeline for multi-stage workflows with loops
See also
OptimizerPass for graph optimization
- __init__(name: str = 'graph') None#
Construct an empty graph.
- Parameters:
name – Human-readable name for profiling and debugging output.
- verify() list[str]#
Every structural invariant this graph and its sub-graphs break, one message each.
Checks that every node id is issued and unique within its graph, that every operand is a registered tensor, that each lifecycle node names the registered tensor it manages, that every node has an executor, and that each contraction and permutation carries index lists as long as its operands’ ranks. Backings are checked both ways: no node may write a tensor whose backing is only read, and a tensor with a write backing must be written, in memory or straight into its storage. Empty for a well-formed graph. Run after every pass when
einsums:pass:verifyis set.
- link_alias_storage() None#
Link a freshly registered handle to any registered tensor whose storage contains it (or that it contains).
cg::view()setsTensorHandle::aliasesitself, but a view sliced OUTSIDE a capture never goes through it: Python’s capture-aware__getitem__falls through to the eager slice, and the resulting view reaches the graph as an ordinary operand on first use. Registered as-is it hasaliases == 0, so the scheduler sees no relationship to its parent and is free to order a read of the parent before a write through the view. That produced silently wrong results with no error, and the pattern is not exotic: a captured view must outlive the graph, which pushes callers to build views up front.So containment is detected here from the registration-time data pointer and strides, which closes the hole whatever the view’s provenance. Runs once over all registered tensors rather than per registration: a containment test is O(n) against what is already there, so doing it on every registration is quadratic, and a DLPNO-MP2 capture registers ~13k tensors. Idempotent and cheap to call; register_tensor just marks it stale.
Note
DELEGATES to
link_alias_structuralwhen no handle in the graph carries an address at all, which is the state of a graph read from a file: nothing is allocated, so there is nothing to compare. Linking nothing there is not a safe default - it is the shape of the full-cover alias bug, a silently incomplete relation that surfaces as a race rather than an error.Note
A MIXED graph - some handles with addresses, some without - is the ordinary case, not an error: a deferred shell has no address until it is materialized, and
TensorHandle::data_ptris a registration-time snapshot nothing refreshes. The rule is that the pointer derivation runs whenever ANY handle carries an address and simply cannot see a null-address handle, unchanged from before, while the structural derivation takes the whole graph only when NONE does. Spanning both modes aredeclare_aliasdeclarations, which are applied first in either and are the only way an alias between two address-less operands is expressible at all.See also
link_alias_structural
- link_alias_structural() None#
Derive the alias relation from
Viewnodes and manifest declarations, with no address consulted anywhere.The counterpart of
link_alias_storagefor a graph that has no addresses to derive from, and the mechanism a loaded graph uses: the structure was read from a file, nothing is allocated, and the tensors bound afterwards are not the tensors that were captured. Writes its result through the same two fields -TensorHandle::aliasesandTensorHandle::alias_box- soresolve_alias, the hazard edges andrebind’s redirect chain consume it unchanged.Two sources, and they are exhaustive because nothing else can survive a save:
``View`` nodes. A
ViewDescriptorsays which parent axis each result axis reads (throughViewDescriptor::permutation) and what interval that axis is restricted to. Chains COMPOSE: a view of a view is placed inside its parent’s own region and linked to the root, the same path compression the pointer derivation does and for the same reason -resolve_aliaswalks the chain on every hazard-scan lookup. A bound that is not a compile-time constant (a Param or a Callback, unknown until execute) yields NO box, so the view conflicts as its whole parent, which is the same conservative answer the pointer path gives for a region it cannot prove.Manifest declarations. Two caller-supplied tensors that share storage with no
Viewnode recording it are declared throughdeclare_alias, whichManifestEntry::aliases_inputcarries across a save. The declaration names a buffer, never a region, so such a pair conflicts as the whole parent until the schema records boxes.
Recurses into
Loopbodies andConditionalbranches, which are separate graphs with their own handles; a body left unlinked answers “this view aliases nothing” and loses its hazard edges silently.Note
Does NOT mark the pointer derivation as done. Running this and then
link_alias_storageon a graph with addresses leaves the relation unchanged, which is the equivalence stated the other way round and is what every scheduling path enforces once this has been called.Note
Idempotent, and safe to run on a graph that HAS addresses - it is then strictly a second opinion, describing the
Viewchains the pointer path skipped (it skips any handle capture already linked) and leaving the pointer-only relations, a reshaped window of a scratch pool among them, tolink_alias_storage. Structural is therefore not a replacement for the pointer derivation on a live graph; it is what a graph with no addresses has instead of one.See also
link_alias_storage
See also
declare_alias
Added in version 2.0.0.
- clear_alias_links() None#
Forget every derived alias link, keeping the declared ones.
Clears
TensorHandle::aliasesandTensorHandle::alias_boxon every handle and marks the relation stale, so the nextlink_alias_storagerebuilds it from scratch. Exists so the two derivations can be compared on the same footing - the equivalence is tested rather than hoped for - and so a loader can install a fresh relation over a graph that carries a stale one.Note
Declarations made through
declare_aliasSURVIVE, because they are an input to the derivation rather than an output of it.Added in version 2.0.0.
- set_space_registry(registry: SpaceRegistry) None#
Resolve this graph’s index spaces against
registryinstead of the global one.Set it BEFORE annotating anything. Ids already stored on this graph’s handles were issued by the previous registry and are not translated.
- Parameters:
registry – The registry to use. It must outlive the graph.
- annotate_spaces(id: int, spaces: list[SpaceId]) None#
- annotate_spaces(tensor: Any, spaces: list[SpaceId]) None
Annotate a registered tensor’s axes with the index spaces they range over.
Annotation is a declaration, so it is checked here, once, rather than on any path that later reads it. Annotate before capturing the operations that use the tensor: capture reads the annotation off the handle to bind the letters of each contraction, and an annotation added afterwards does not reach nodes that are already recorded.
- Parameters:
id – The tensor to annotate.
spaces – One space per axis, in axis order. Pass an empty vector to clear the annotation. Every axis must name a real space; to leave one axis unannotated, see
annotate_space_axis.
- Raises:
- annotate_space_axis(id: int, axis: int, space: SpaceId) None#
Annotate ONE axis, leaving the others as they are.
annotate_spacestakes THE COMPLETE annotation and rightly refuses a hole in it: a caller handing over a whole vector has said something about every axis, and an invalid id in one slot is far more likely a mistake than an intention. This is how the hole is made deliberately, one axis at a time, for a tensor that mixes axes over a space with axes whose extent is a fixed number meaning nothing chemically - a DIIS history depth beside a pair of orbital indices. Axes nobody has named stay unannotated, which every reader of the annotation already handles per axis.Added in version 2.0.0.
- tensor_spaces(id: int) list[SpaceId]#
- tensor_spaces(tensor: Any) list[SpaceId]
The index spaces annotated on a registered tensor’s axes.
- Parameters:
id – The tensor to read.
- Returns:
One space per axis, or an empty vector when the tensor carries no annotation.
- Raises:
Exception – if no tensor with that id is registered.
- annotate_tag(id: int, tag: ProvenanceTag) None#
- annotate_tag(tensor: Any, tag: ProvenanceTag) None
Declare what a tensor IS, by name.
Index spaces say how big a tensor’s axes are; this says what the tensor is, which is the question a pass that wants to RECOGNIZE something has to ask.
DeltaEliminationlooks forprovenance_identity; a factorization provider will look for its own name.The vocabulary is open and unvalidated on purpose, because the set of things worth recognizing grows with the passes that recognize them. The cost is real and worth stating: a misspelled name is a tag nothing matches, and the only symptom is a pass that quietly finds no candidates. A pass is expected to report that through its skip tally rather than to stay silent.
Attributes are sorted on the way in, so two tags built by setting the same keys in a different order compare equal and a saved graph’s bytes do not depend on call order.
Added in version 2.0.0.
- Parameters:
id – The tensor to tag.
tag – The tag. An empty name clears any tag the tensor carried.
- Raises:
Exception – if no tensor with that id is registered.
- tensor_tag(id: int) ProvenanceTag#
- tensor_tag(tensor: Any) ProvenanceTag
What a registered tensor is declared to be.
Added in version 2.0.0.
- Parameters:
id – The tensor to read.
- Returns:
The tag, whose
ProvenanceTag::nameis empty for an untagged tensor.- Raises:
Exception – if no tensor with that id is registered.
- annotate_backing(tensor: Any, backing: TensorBacking) None#
Declare a tensor’s backing, addressing it by the caller’s tensor object.
Added in version 2.0.0.
- Parameters:
tensor – The tensor, declared on this graph and still deferred.
backing – The storage.
- tensor_backing(tensor: Any) TensorBacking | None#
The storage a tensor is backed by, addressing it by the caller’s object.
Added in version 2.0.0.
- Parameters:
tensor – The tensor to read.
- Returns:
The backing, or nothing.
- Raises:
Exception – if this graph has never seen that tensor.
- space_extent(space: SpaceId) int | None#
The extent this graph has learned for
space, if it knows one.Learned, not declared:
annotate_spaceson a tensor whose dims are concrete says how big that space is on this problem, so the graph records it rather than making the caller repeat it. Two annotated axes over one space that disagree leave the space UNPINNED, which is not an error - a PNO domain legitimately has a different extent per pair - but it does mean a space-typed dimension cannot be sized from it.See also
declare_zero_runtime_tensor(std::string, std::vector<SpaceDim>, bool)
Added in version 2.0.0.
- Parameters:
space – The space to ask about.
- Returns:
The extent, or an empty optional when no annotated tensor has pinned it or when two of them disagree.
- space_tiling(space: SpaceId) list[int] | None#
How
spaceis canonically cut up, if this graph has been told.A tiled program usually cuts one space the same way everywhere - every occupied axis in a tiled CC lands on the same block boundaries - so the partition is worth saying ONCE, at the space, instead of at every tensor that has such an axis. Retiling is then one edit rather than one per declaration.
Unlike
space_extentthis is never learned: a tensor’s tiling is a property of that tensor, and taking the first one seen as canonical would silently make one scratch buffer’s layout everyone else’s.See also
pin_space_tiling
Added in version 2.0.0.
- Parameters:
space – The space to ask about.
- Returns:
The tile sizes, or an empty optional when none was stated or two statements disagreed.
- pin_space_tiling(space: SpaceId, tile_sizes: list[int]) None#
State how
spaceis cut up, for every tiled axis that ranges over it.Also pins the extent to the sum, because a partition states one: a space cut into
{2,2}measures 4, and leaving those two facts able to disagree would be a bug waiting to happen.Added in version 2.0.0.
- Parameters:
space – The space.
tile_sizes – The partition. Empty clears it.
- Raises:
Exception – If
spaceis invalid, if any tile is not positive, or if the tiles sum to something other than an extent already known forspace.
- pin_space_extent(space: SpaceId, extent: int) None#
State what
spacemeasures on this problem, rather than waiting to learn it.For the graph whose first tensor over a space is the one being declared, so there is nothing to have learned from yet. A later disagreeing annotation still unpins the space.
Added in version 2.0.0.
- Parameters:
space – The space.
extent – Its extent. Zero clears whatever was known.
- annotate_dims(id: int, symbols: list[str]) None#
- annotate_dims(tensor: Any, symbols: list[str]) None
Declare which of a tensor’s extents a
bindmay move, and which move together.The extent counterpart of
annotate_spaces, and what makes a captured graph valid for a family of problem sizes rather than for the one geometry it was captured at.rebindrejects any dim mismatch, which is right for a same-problem pointer swap and fatal for cross-problem reuse; a symbol is how a caller says “this axis isnv, whatevernvturns out to be next time”.Symbol-space ties
When an annotated axis also carries a
annotate_spacesannotation, the pair(symbol, space)is recorded. One symbol tied to two different spaces anywhere in one graph is a contradiction -nvcannot be both the virtual space and the auxiliary basis - and is refused here, where both spaces are still in hand, rather than surfacing as an unsolvable bind. The tie is recorded from either side, so annotating spaces after dims catches it too.See also
bind
See also
symbol_spaces
Added in version 2.0.0.
- Parameters:
id – The tensor to annotate.
symbols – One entry per axis, in axis order. The empty string leaves an axis LITERAL (a bind must match it exactly). Any other string names a symbol: every axis in this graph carrying that symbol has one extent, and a bind solves it. A
"ragged:<space>"spelling (seemake_ragged_symbol, or useannotate_ragged_dim) marks an axis whose extent differs per instance. Pass an empty vector to clear the annotation.
- Raises:
- annotate_ragged_dim(id: int, axis: int, space_name: str) None#
- annotate_ragged_dim(tensor: Any, axis: int, space_name: str) None
Declare one axis ragged over an index space.
One symbol per space is not enough for the workload that motivates symbolic extents: a PNO domain has a different virtual extent per pair, and a block or tiled tensor carries per-block dims, so no single
nvdescribes them. A ragged axis says so explicitly instead of pretending otherwise - it constrains nothing across slots, and a bind accepts whatever extent each bound instance carries.Sugar over
annotate_dims: it writesmake_ragged_symbolintoaxisof the tensor’s existing symbol vector, creating an all-literal one first if the tensor has none.See also
bind_ragged_extents
Added in version 2.0.0.
- tensor_dim_symbols(id: int) list[str]#
- tensor_dim_symbols(tensor: Any) list[str]
The symbolic extent declaration on a registered tensor’s axes.
Added in version 2.0.0.
- Parameters:
id – The tensor to read.
- Returns:
One entry per axis, or an empty vector when every axis is literal.
- Raises:
Exception – if no tensor with that id is registered.
- execute() None#
- execute(executor: Executor) None
Execute all nodes in topological order.
Performs topological sorting (if not already sorted), validates that all tensor pointers are still alive, then executes each node’s lambda in order.
Can be called multiple times to replay the same computation sequence. All tensors must have the same dimensions as at capture time.
- set_executor(executor: Executor) None#
Choose the executor plain execute() uses for THIS graph.
The stored executor applies wherever this graph is executed without an explicit executor argument - most importantly loop bodies, which are replayed by the loop node via the argument-less execute() and had no other way to run on a parallel backend:
body = g.add_loop("iter", 100, cont) body.set_executor(cg.DataflowExecutor()) # replays overlap independent nodes
Pass nullptr/None to restore the built-in sequential path. The custom executors dispatch every node’s CPU lambda directly, so graphs with GPU-placed nodes should keep the default (it performs the device shadow bookkeeping; the executors do not).
- Parameters:
executor – Shared ownership of the executor, or nullptr to reset.
- apply(pm: PassManager) bool#
Apply a PassManager (ordered sequence of passes) to the graph.
Runs all passes in the PassManager in order.
auto pm = cg::PassManager::create_default(); graph.apply(pm);
- Parameters:
pm – The pass manager to run.
- Returns:
True if any pass modified the graph.
- optimize() bool#
- optimize(level: OptLevel) bool
Optimize with the full default pipeline (OptLevel::O2).
Compiler-style front door over PassManager: builds the pipeline, runs it, and records a human-readable summary retrievable via explain().
graph.optimize(); std::cout << graph.explain();
- timing_report() list[NodeTiming]#
Access the timing data from the last execute() call. Labels are resolved here (cached until the next recorded sample), not on the replay path.
- Returns:
One entry per node the last replay ran, in run order.
- last_run() RunMetrics#
What the last completed replay did, measured as it ran.
Assembled when asked for, from counts the replay kept: nodes add their times as every executor already records them, a backing counts its own reads and writes on whichever thread runs them, and lifecycle nodes count what they allocate and free.
See also
RunMetrics
Added in version 2.0.0.
- Returns:
Time per node (this graph’s and every body’s, a loop body’s summed over its iterations), bytes and calls per backing, and the most graph-managed memory held at once. Empty before the first replay; a replay that threw leaves the one before.
- resident_bytes() int#
The bytes a replay holds from its start to its end that no lifecycle node of it allocates or frees.
The other half of the program’s memory beside
RunMetrics::peak_bytes, which counts what the lifecycle nodes hold. Their sum is what the budget check compares with –einsums:max-memory.Added in version 2.0.0.
- Returns:
The bytes of every tensor this graph and its bodies read or write that is in memory for the whole replay: the caller’s tensors, and any intermediate given storage outside a Materialize node. Each tensor once; views and tensors a Materialize or Free node manages are left out. A backed tensor is read and written through buffers those nodes manage, so its stored bytes are not counted.
- set_observer(observer: ExecutionObserver) None#
Attach
observerto every replay of this graph and of every body under it.The observer belongs to the graph’s tree, so attaching it to a body attaches it to the graph that holds the body too. Attach between replays, not during one.
See also
ExecutionObserver
See also
EventLog
Added in version 2.0.0.
- Parameters:
observer – What hears the replays; null detaches the one attached.
- to_dot() str#
The GraphViz text
print_dotwrites, as a string.Added in version 2.0.0.
- Returns:
The DOT source.
- summary() str#
The summary
print_summarywrites, as a string.Added in version 2.0.0.
- Returns:
The summary text.
- to_json() str#
Serialize the graph structure as a JSON string.
Produces a JSON object with:
“name”: graph name
“tensors”: array of {id, name, rank, dims, element_size, dtype, is_intermediate}
“nodes”: array of {id, kind, label, inputs, outputs, timing_ms}
“edges”: array of {from_node, to_node, tensor_id} (data dependency edges)
Used by the profile viewer to render an interactive node graph. Can be called at any point, edges are computed on-the-fly from node inputs/outputs, so this works both before and after execute().
- Returns:
JSON string representation of the graph structure.
- serializability_report() list[SerializabilityBlocker]#
The nodes that stand between this graph and being saved, with the reason for each.
A graph can be written to a file only when every node can be rebuilt from
(kind, dtype, rank, descriptor, operand ids)- seebuild_executor. Conversion is per op kind and deliberately incremental, so “can this graph be saved” has an actionable answer rather than a boolean: this names each node that cannot, by id and label, and says what blocks it.Note
Recursive: a
Loopbody and eachConditionalbranch is a separate sub-graph and is descended into, withSerializabilityBlocker::subgraph_pathnaming the path that reaches each blocker. The earlier flat version was justified by Loop and Conditional always blocking on their own closure-shaped predicates, which made a body unreachable-but-unreported an impossibility. Making both predicates data (PredExprandBoundExpr), so a clean control-flow node over a body full of closures now reports clean, and the justification is gone.See also
reconstruction_blocker for the per-node verdict.
Added in version 2.0.0.
- Returns:
One entry per blocking node, in node order, a control-flow node’s own verdict immediately before its body’s. Empty means the graph and everything below it is fully reconstructible.
- content_hash() int#
A hash of this graph’s STRUCTURE, and of nothing else.
The digest of the canonical IR bytes with the provenance block removed: schema version, graph name, manifest, index spaces, parameters, gate-flag arrays, tensors, slot redirects and nodes. Two captures of the same program hash equal however they were produced and whoever wrote them; any structural difference - a changed prefactor, a reordered node, a renamed slot - changes the hash.
Note
Provenance-independent BY CONSTRUCTION rather than by convention: the hash is taken over the same object the writer emits, minus one key, so a field can only enter the hash domain by being put in the structure sections.
See also
save_graph
Added in version 2.0.0.
- Returns:
The digest.
- Raises:
Exception – When the graph cannot be written at all (see
serializability_report), because a structure that has no canonical form has no hash either. The message carries the report.
- schedule_edge_count() int#
How many hazard edges the schedule holds, and how wide its levels are.
The two structural numbers a change to the dependence machinery moves: an access that cannot be described precisely widens to its whole buffer and picks up edges against every other access to it, and those edges are what cost a level scheduler its width. Both are deterministic, so they are what a test about ordering should assert - and what a measurement of ordering should report - rather than a wall clock or an energy.
Both build the schedule if it is stale, exactly as
execute()would, and so may reorder nodes into a topological order.Added in version 2.0.0.
- Returns:
schedule_edge_countthe number of dependency edges;schedule_level_sizesthe size of each level in order.
- unjustified_hazard_edges() list[str]#
Hazard edges that nothing about the storage justifies.
verify_level_independenceasks whether an edge is MISSING, and every alias defect this module has shipped was found by it or by a race. The opposite direction has no detector at all, and it is the direction an over-conservative alias relation fails in: merging two unrelated tensors into one root costs a level scheduler its width and moves no number, so no differential oracle can see it. The deferred-parent merge cost every hazard between the two parents and was invisible for exactly that reason.The justification is derived WITHOUT consulting
TensorHandle::aliases, which is the relation under test. Two tensors may share memory when they are the same tensor, when one is reachable from the other through the graph’s ownViewnodes, or when both have a known byte span and the spans overlap. A pair with none of those and no shared parameter name has no reason to be ordered.A tensor with no address is therefore related to another only structurally, which is what makes this see the deferred case: two deferred parents have no spans, so an edge between their writers can only come from an alias link that should not exist.
Builds the schedule if it is stale, exactly as
schedule_edge_countdoes.Added in version 2.0.0.
- Returns:
One line per unjustified edge, naming both nodes; empty when the edge set is minimal.
- structural_passes() list[str]#
The structural-algebraic passes that have rewritten this graph, in order.
Survives a save and a load, so a graph loaded from a file reports what shaped it before it was written rather than starting blank.
Added in version 2.0.0.
- Returns:
The names, empty on a graph nothing has rewritten.
- machine_dependent_passes() list[str]#
The structural-resource and tuning passes that have changed this graph, in order.
Added in version 2.0.0.
- Returns:
The names, empty on a graph only capture and the structural passes have shaped.
- approximations() list[ApproximationRecord]#
Every lossy rewrite applied to this graph, in the order it was applied.
Saved with the structure and restored by a load, because a record says what the graph now computes rather than how it runs. Unlike
structural_passes, which is provenance and is read by nobody, these ARE acted on: a second lossy pass composes against them, and a tolerance-aware comparison widens by them.See also
note_approximation
Added in version 2.0.0.
- Returns:
The records, empty on a graph nothing has approximated. An empty list is EXACT mode: a differential comparison against eager stays at bit equality.
- note_approximation(record: ApproximationRecord) None#
Record a lossy rewrite this graph has just had applied.
A pass asks
can_approximateBEFORE it rewrites anything, and declines throughOptimizerPass::approximatewhen the answer is no.Added in version 2.0.0.
- Parameters:
record – What the rewrite was and what it cost. See
ApproximationRecord.- Raises:
Exception – With the reason, when
can_approximaterefuses it. Throwing rather than returning a flag, because a pass reaching here has already rewritten the graph: a refusal at this point is a pass that did not ask first, and the graph it leaves behind is wrong in a way no return value would fix.
- can_approximate(candidate: ApproximationRecord) str#
Whether a pass may apply
candidate, and why not when it may not.Three ways the answer is no, and each is a real case rather than a guard against nonsense input:
The bound is negative or not finite. A pass that cannot state its effect has not met the contract, whatever else it can do.
The composed bound exceeds the declared budget for some output it names.
A budget is set and a record of a DIFFERENT effect already covers an output this one names. Only under a budget: bounds of different kinds coexist happily otherwise, and the tolerance carries them on separate sides. What a budget adds is a claim to be a cap, and a cap that governs one kind of error while another goes uncounted is misleading in a way that saying so is not.
A graph with no budget therefore refuses only the first case: adding a lossy pass to a manager is the opt-in, and a budget is the further cap on what several may spend together.
What is NOT decided here is whether a pass’s own error model still holds once something else has perturbed its inputs. Only that pass knows;
approximationsis readable so it can look, and it declines throughOptimizerPass::approximatelike any other refusal.See also
set_accuracy_budget
Added in version 2.0.0.
- Parameters:
candidate – The rewrite a pass is about to apply.
- Returns:
An empty string when it may; otherwise the reason, phrased for a skip tally.
- accuracy_spent(effect: ApproximationEffect, output: str = '') float#
The composed bound already spent on one output.
Added in version 2.0.0.
- Parameters:
effect – The units to answer in. Records of other effects are not counted, because they do not convert.
output – The manifest name to ask about, or empty for the graph-wide worst case, which counts every record whatever it names.
- Returns:
The composed bound, 0 when nothing applies.
- approximation_tolerance(output: str = '') ApproximationTolerance#
The comparison tolerance this graph’s records imply for one output.
The point of entry for Part 5.4’s tolerance-aware differential mode, and the reason it lives here rather than in the harness: composition is arithmetic with a correctness argument behind it (see
compose_approximation), and a second implementation of it in the test layer would be a second thing to get right.Added in version 2.0.0.
- Parameters:
output – The manifest name to ask about, or empty for the graph-wide worst case.
- Returns:
The relative and absolute halves. Both zero on a graph with no records, which is exact mode.
- set_accuracy_budget(effect: ApproximationEffect, value: float) None#
Cap what lossy passes may spend on this graph, together.
Not set by default, and the default is not zero: a lossy pass runs only because a caller put it in a manager, and that is the opt-in. This is the second guard, for the caller who wants several of them and a ceiling on what they cost together.
See also
clear_accuracy_budget
Added in version 2.0.0.
- Parameters:
effect – The units the cap is stated in. A pass bounding itself in any other effect will decline rather than convert.
value – The largest composed bound any single output may carry.
- Raises:
Exception – If
valueis negative or not finite.
- plan_threads(freeze: bool = False) bool#
Choose a thread width for every node, for this machine, now.
Runs the
passes::ThreadPlanningheuristic standalone - no pipeline needed, because widths touch no structure - and records the thread count the plan assumed soDataflowExecutorcan notice a machine change and fall back to width 1. Loop bodies and conditional branches are planned too, each against the same thread count; the one process-wide width budget composes them at run time.Only
DataflowExecutoracts on the result. Under the other executors the graph behaves exactly as an unplanned one.Re-plan policy
A plan needs per-node serial times, and the honest ones are measured - but a measurement is taken under whatever plan and whatever concurrency produced it, so a plan computed FROM those timings and the plan they were measured UNDER are never comparable on paper: the re-plan’s own estimate is polluted by the incumbent’s schedule. (Concretely: co-run contention inflates every sample, the inflated area bound swallows the critical path, and a timings re-plan can then only ever narrow - it un-widened measurably profitable plans in every DLPNO trial.) The one comparator that settles it is the wall clock, so the re-plan is a measured trial rather than a decree:
A graph that has already replayed is planned from its recorded timings, and that plan is final.
A graph that has never replayed is planned from the cost model. Replay 1 warms up and records timings, and a re-plan is computed from them; if it chooses the same widths the trial ends there (keeping the re-plan’s measured admission priorities). Otherwise replay 2 runs the re-planned widths, replay 3 runs the cold widths again - both steady-state - and the graph keeps whichever replay was faster, the incumbent unless the candidate clearly beat it. A trial the workload never finishes (fewer than three replays) leaves the cold plan in place.
The consequence is deliberate and is the determinism contract: widths move only inside the trial window, so from the fourth replay onward - or from the first, with
freeze- repeated replays at a fixed thread count are bit-identical.Added in version 2.0.0.
- Parameters:
freeze – Plan now and never re-plan, even from the cold-start model. For workflows that want every replay bit-identical to the first, at the cost of model-quality widths.
- Returns:
True when at least one node was given a width above 1.
- add_conditional(label: str, predicate: Callable[[Any], bool]) tuple[Graph, Graph]#
Add a conditional (if-then-else) node to the graph.
Returns references to the then-branch and else-branch subgraphs. Use CaptureGuard on each to capture operations into the branches. The predicate is evaluated at execution time to select the branch.
auto [then_g, else_g] = graph.add_conditional("converge_check", [&]() { return delta < threshold; }); { CaptureGuard g(then_g); cg::scale(1.0, &result); } { CaptureGuard g(else_g); cg::einsum(...); }- Parameters:
label – Human-readable label for profiling.
predicate – Function returning true for then-branch, false for else-branch. Can inspect tensor values and external state.
- Returns:
Tuple of references: (then_branch_graph, else_branch_graph). A tuple (not a pair) so the method can be bound to Python, pybind11 can’t cast a pair/tuple of references to a non-copyable type cleanly, but a reference-tuple return casts each branch with
reference_internal. Structured bindings (auto [t, e] = ...) work identically for C++ callers.
- add_conditional_flag(label: str, flags: GateFlags, index: int) tuple[Graph, Graph]#
Add a conditional whose predicate is one flag of a
GateFlagsarray.The same node
add_conditionalbuilds, with the predicate replaced by a load from a shared buffer. Use it when the answers are known before the replay starts and there are many of them: astd::functionbound to a Python callable takes the GIL every time it is evaluated, and a graph whose conditionals run on several threads serializes on that.The array is shared, not copied, so the caller may keep writing to it between replays; a copy of the
shared_ptris baked into the node, so the flags outlive the handle. An index past the end of the array reads false.- Parameters:
label – Human-readable label for profiling.
flags – The array to read.
index – Which flag in it selects this node’s branch.
- Returns:
Tuple of references: (then_branch_graph, else_branch_graph).
- add_loop(label: str, max_iterations: int, condition: Callable[[int], bool]) Graph#
- add_loop(label: str, max_iterations: int, condition: Callable[[int], bool], body_fn: Callable[[Any], None]) None
Add a loop node to the graph (Graph-returning variant).
Returns a reference to the loop body subgraph. Use CaptureGuard to capture operations into the body.
- Parameters:
label – Human-readable label for profiling.
max_iterations – Maximum number of iterations (safety limit).
condition – Called after each iteration with the iteration number.
- Returns:
Reference to the loop body Graph.
- add_setup(label: str) Graph#
- add_setup(label: str, body_fn: Callable[[Any], None]) None
Add a setup node: a body computed once per bound problem, not once per replay.
Returns the body sub-graph, to be captured into with a
CaptureGuardexactly as a loop body is. What goes in it is the computation that depends on WHAT is bound rather than on how many times the graph is replayed: a density fitting, a metric inverse, an integral transform. The replay body then reads its outputs and never recomputes them.Structurally this is a control-flow node like any other, which is the point: it takes its position in the ordinary schedule, its effective I/O is the sub-graph’s reads and writes (so the scheduler orders it before every consumer with no special case), and a pass that walks sub-graphs reaches it through
for_each_subgraph. What is special is only the executor, which skips a body that has already computed.When the body runs
At the first
executeafter capture, and at the firstexecuteafter anybind. It is not run BY the bind: a bind that is never executed should cost nothing, and a caller who wants the factors on hand earlier callsrun_setup.What a setup output must not be
Its outputs live across replays, so nothing may free them between two. @ref passes::FreeInsertion is told this rather than left to infer it from a live range that looks, within one replay, exactly like an ordinary intermediate’s.
auto &fit = graph.add_setup("df_fit"); { cg::CaptureGuard const guard(fit); cg::einsum("Qmn <- QP ; Pmn", &B, metric_inv_sqrt, ints); } // ... the replay body reads B ... graph.execute(); // fits, then replays graph.execute(); // replays onlySee also
run_setup
See also
set_setup_key
See also
invalidate_setup
Added in version 2.0.0.
- Parameters:
label – Human-readable label for profiling and diagnostics.
- Returns:
Reference to the setup body Graph. Valid for the life of this graph.
- run_setup(force: bool = False) None#
Run every setup body that is not current, now.
What the next
executewould do anyway, pulled forward for a caller who wants the fitting cost paid at a moment of their choosing rather than inside the first replay’s timing. Nothing else differs: the same guards apply, so a body already computed for the bound problem is skipped here exactly as it would be there.Added in version 2.0.0.
- Parameters:
force – Run every body whatever its state, ignoring both the computed flag and the key. The escape hatch for a caller who changed the CONTENTS of a bound tensor without rebinding it, which nothing can observe.
- invalidate_setup() None#
Mark every setup body as needing recomputation.
Called by
bind, which is the one event that can change what a setup body would produce. Public because a caller who mutates a bound tensor in place has made the same change without going through a bind, and nothing else can see that.Added in version 2.0.0.
- set_setup_key(key: str) None#
Name the problem currently bound, so a re-bind of it can skip refitting.
The cache of the setup phase, and a claim the caller makes rather than one this graph checks. A bind invalidates every setup body; if the key set here is non-empty and equal to the key the body last computed for, the body is skipped anyway on the ground that the caller has said this is the same problem.
Empty (the default) disables the cache: every bind refits, which is always correct. A caller supplying a key owns the consequence of supplying the same one for two different problems, which is a stale factorization and no diagnostic. Use something that identifies the problem rather than the call: a molecule and basis, a checkpoint id, a content hash the caller computed for its own reasons.
Added in version 2.0.0.
- Parameters:
key – The problem identity, or empty to disable the cache.
- create_runtime_tensor(name: str, dims: list[int], intermediate: bool = True) GeneralRuntimeTensor#
Create a graph-owned runtime-rank tensor.
Runtime-rank analog of create_tensor(). Allocates a RuntimeTensor<T, Alloc> with rank determined by dims.size(), no rank-4 cap, no compile-time rank in the type. Adds an Alloc node and marks the handle as intermediate. Lives for the lifetime of the graph.
auto &tmp = graph.create_runtime_tensor<double>("tmp", {100, 100}); auto &big = graph.create_runtime_tensor<double>("big", {2, 3, 4, 5, 6}); // rank-5, fine
- create_zero_runtime_tensor(name: str, dims: list[int], intermediate: bool = True) GeneralRuntimeTensor#
- create_zero_runtime_tensor(name: str, shape: list[SpaceDim], intermediate: bool = True) GeneralRuntimeTensor
Runtime-rank analog of create_zero_tensor().
- declare_runtime_tensor(name: str, dims: list[int], intermediate: bool = False, backing: TensorBacking | None = None) GeneralRuntimeTensor#
- declare_runtime_tensor(name: str, shape: list[SpaceDim], intermediate: bool = False, backing: TensorBacking | None = None) GeneralRuntimeTensor
- declare_runtime_tensor(name: str, backing: TensorBacking, intermediate: bool = False) GeneralRuntimeTensor
Declare a graph-owned runtime-rank tensor with DEFERRED allocation.
The runtime-rank, pybind-exposed analog of declare_tensor(): a shell tensor (valid metadata, no data) registered in THIS graph’s tensor map with AllocState::Deferred. No Alloc node is inserted, the MaterializationPass inserts Materialize+Initialize at the right position, and MemoryPlanning / FreeInsertion / InplaceOptimization can then plan, reuse, and free its buffer (unlike create_*_tensor, which is allocated eagerly and so is opaque to those passes). Use this for graph/loop-body scratch you want the memory passes to manage.
- Parameters:
name – The tensor’s name.
dims – Its extents.
intermediate – Whether nothing reads the tensor after
execute(). A tensor declared without it is a RESULT: the caller may read it once the graph has run, so it has to exist whole then, andAxisTilingleaves it whole however large, naming it in its report when it is over the memory budget. Declare every tensor the program builds only for its own use as an intermediate, so the graph may stream it in blocks and never hold it whole.backing – Storage the tensor lives in, as
annotate_backingtakes it. Passing it here is the same as annotating the declared tensor, except that a refused backing leaves nothing declared.
- Returns:
The declared tensor, owned by this graph.
- Raises:
Exception – As
annotate_backing, whenbackingis refused.
- declare_zero_runtime_tensor(name: str, shape: list[SpaceDim], intermediate: bool = False, backing: TensorBacking | None = None) GeneralRuntimeTensor#
- declare_zero_runtime_tensor(name: str, dims: list[int], intermediate: bool = False, backing: TensorBacking | None = None) GeneralRuntimeTensor
Declare a deferred graph-owned tensor whose shape is stated in index spaces.
The three statements a space-shaped scratch tensor needs today, collapsed into the one that cannot disagree with itself:
// Today - three calls, three chances to drift apart: auto &T = graph.declare_zero_runtime_tensor<double>("T", {4, 8}); graph.annotate_spaces(T, {occ, virt}); graph.annotate_dims(T, {"occ", "virt"}); // Here: auto &T = graph.declare_zero_runtime_tensor<double>("T", {occ, virt});What the axes are annotated with
A space-typed axis is annotated with that space AND given a dim symbol, so the tensor is rebindable at new extents without a second call. The symbol is the space’s
IndexSpace::dim_symbol, declared once at registration; a space registered without one is refused here rather than having a name invented for it. A numeric axis is left literal and unannotated, which is what a fixed size means.See also
SpaceDim
See also
annotate_dims
Added in version 2.0.0.
- Parameters:
name – Human-readable name.
shape – One entry per axis: an index space, or a number for an axis that is genuinely a fixed size.
SpaceDimconverts from both.intermediate – Whether the tensor is graph-internal scratch.
backing – A write backing; see the dims overload.
- Returns:
Reference to the deferred tensor.
- Raises:
Exception – If a named space has no extent this graph has learned (see
space_extent): either nothing annotated over it yet, in which casepin_space_extentsays so directly, or two annotated axes disagree, which is what a ragged family looks like and wantsannotate_ragged_diminstead.
- declare_zero_tiled_tensor(name: str, tile_sizes: list[list[int]], intermediate: bool = False) TiledRuntimeTensor#
- declare_zero_tiled_tensor(name: str, shape: list[SpaceTiling], intermediate: bool = False) TiledRuntimeTensor
Tiled analog of declare_zero_runtime_tensor(): a graph-owned TiledRuntimeTensor shell over
tile_sizeswith DEFERRED lifecycle.The shell starts with no populated tiles - ops create tiles on demand (infer-and-create, zeroed) - so Materialize and Initialize are cheap, but registering the handle as Deferred puts the tensor under the same lifecycle machinery as dense scratch: Materialization hoists the pair to the loop’s parent, and FreeInsertion can release the tile storage after the last consumer (release() keeps the sparsity pattern, so a later replay re-materializes into the same structure). MemoryPlanning leaves tiled scratch alone by construction: the arena requires materialize_into, and a tile-wise tensor has no single buffer to place. Scratch REUSE per replay is safe for the ops with the leftover-scale rule (einsum’s c_pf, direct_division’s and permute’s beta apply to every stored tile, so stale tiles from a previous iteration are zeroed, not kept).
- declare_internal_tensor(name: str, dims: list[int]) GeneralRuntimeTensor#
Declare a deferred intermediate on a caller’s behalf.
For a helper that adds tensors the caller never sees, such as the partial products of an einsum over three or more operands. It is an ordinary declared intermediate to every pass, so
AxisTilingmay build it a block at a time andMaterializationgives it storage or leaves it without any once nothing uses it. Unlike a tensor the caller declared, it does not make a graph run without those passes fail: its firstexecute()gives it storage when a node still reads or writes it and no Materialize node does.Added in version 2.0.0.
- Parameters:
name – The tensor’s name.
dims – Its extents.
- Returns:
The declared tensor, owned by this graph.
- scratch_runtime(name: str, dims: list[int]) GeneralRuntimeTensor#
Runtime-rank scratch (see scratch(); pybind-facing analog).
- scratch_zero_runtime(name: str, dims: list[int]) GeneralRuntimeTensor#
Runtime-rank zero-initialized scratch.
- bind_begin() None#
Begin a multi-slot bind, to be finished by
bind_commit.bindis variadic and cannot be bound to Python, and calling the one-pair spelling once per slot is NOT the same operation: a dim symbol is a constraint ACROSS slots, so a caller moving a problem’s extents has to hand over every slot before any of them is reconciled. Binding them one at a time solves each against a half-updated interface and fails with operands that “describe two different problems”.These three calls are that transaction, opened up so a caller without variadics can drive it:
bind_begin, thenbind_addonce per slot, thenbind_commit. Nothing is repointed until the commit, so a refusal leaves the graph as it was.Note
Each added tensor must outlive the commit; only a reference is kept.
See also
bind_add
See also
bind_commit
Added in version 2.0.0.
- bind_add(name: str, tensor: Any) None#
Add one slot to the bind opened by
bind_begin.Added in version 2.0.0.
- Parameters:
name – The manifest name of the slot.
tensor – The storage to bind. Must outlive the commit.
- Raises:
Exception – When no bind is open.
- bind_commit() None#
Finish the bind opened by
bind_begin, as one transaction.Added in version 2.0.0.
- Raises:
Exception – As
binddoes, with nothing repointed.
- bind_slot(name: str, tensor: Any) None#
Bind ONE named slot, the spelling a binding can carry.
bindis variadic, which is right for a C++ caller and unbindable from Python; this is the same operation with one pair, applied through the same solver. Call it once per slot.See also
bind
Added in version 2.0.0.
- Parameters:
name – The manifest name of the slot.
tensor – The storage to bind.
- manifest_names() list[str]#
Every manifest binding key, in the manifest’s own order.
The whole
InterfaceManifestis a richer object than a binding needs; this is the part a caller binds by, and it is what the Python surface exposes so a driver can walk a loaded graph’s interface without the manifest type having to be bound too.Added in version 2.0.0.
- Returns:
The names.
- manifest() list[ManifestEntry]#
Every slot of
manifestonce, in its order: what Python sees asmanifest().Added in version 2.0.0.
- Returns:
The entries, an
InOutslot once.
- bind_ragged_extents(name: str, axis: int, extents: list[int]) None#
Supply the per-instance extents of one ragged axis.
A ragged axis (see
annotate_ragged_dim) has no scalar extent to solve, so this is what a caller hands the graph in place of one: the design’s “bindsupplies a per-instance extent table rather than a scalar”.Note
ACCEPTED and STORED, not yet consumed, and the task is larger than it first looked. The nodes that read such a table are the grouped/batched ones, and the original plan was that the resource phase re-forms them at load from the table. That assumes grouped nodes are a resource-phase PRODUCT. They are not:
grouped_batched_gemmis a capture-time API and the workload that needs this (DLPNO) calls it directly, so there is no pre-resource algebraic form underneath to fall back to. Worse, a grouped batch partitions its members by SHAPE at capture and reorders the operand lists to match, so moving the extents changes the partition itself and not merely the numbers in it.Consuming the table therefore waits on a decision recorded in the design doc: either capture the per-member algebraic form and add a pass that groups it, or keep the grouped form and teach it to re-derive its own partition. Until then a graph containing a grouped node refuses to save, saying so, and the table is available through
ragged_extent_tablesand nothing else reads it.See also
clear_bindings
Added in version 2.0.0.
- Parameters:
name – The manifest name of the slot.
axis – Which axis of that slot the table describes.
extents – One extent per instance of the axis’s space, in instance order.
- Raises:
Exception – If
nameis not a manifest entry; ifaxisis past its rank or is not declared ragged; ifextentsis empty; or if another table already stored for the SAME space has a different length. The length is the instance count, which is a property of the space (how many pairs there are) and not of one operand, so two tables over one space disagreeing about it describes nothing.
- space_registry: SpaceRegistry#
The registry this graph resolves index spaces against.
A graph annotated against one registry must be queried against the same one: a
SpaceIdis a handle into the registry that issued it and means nothing anywhere else. The process-global registry is the default precisely so that the common case never has to think about it; a test (or a capture that wants an isolated set of spaces) overrides it.(read-only)
- explain: str#
What the last optimize() did, as a human-readable report.
Node counts before/after plus the per-pass highlights (chains restructured with estimated speedups, buffers merged in place, Frees inserted, arena size vs the buffers it hosts, batches formed and profitability-gate skips). Empty until optimize() has run.
(read-only)
- decisions: list[Decision]#
What the last optimize() decided, as records: the ones
explainprints from.Added in version 2.0.0.
(read-only)
- accuracy_budget_value: float#
The budget’s value, for a caller that cannot hold an optional pair.
Added in version 2.0.0.
(read-only)
- planned_thread_count: int#
Threads the per-node widths on this graph were planned against.
A width is chosen for one machine at one moment: the planner divides a known number of threads between the nodes, so the same widths on a different thread count are not a worse plan, they are a wrong one. Recording the count the plan assumed lets
DataflowExecutornotice and fall back to running every node at width 1.0 means nothing recorded, which is what a hand-set width or an unplanned graph looks like; those are honored as they are found. Deliberately not serialized with the graph, for the same reason the widths are not.
(read-only)
- thread_replan_armed: bool#
Whether the thread plan is still inside its measured trial window: a re-plan is waiting for the next completed replay, or the trial replays are still being timed. False once the widths are final. @see plan_threads
(read-only)
- class einsums.graph.GrowthClass#
How a space’s extent grows with the size of the system.
The extent scales as
N^exponentfor system sizeN(constant,linear,power). Advisory: lets a pass rank contraction orders before extents are bound.- static constant() GrowthClass#
A space whose extent does not grow with the system (exponent 0).
- Returns:
The constant growth class.
- static linear() GrowthClass#
A space whose extent grows proportionally with the system (exponent 1).
- Returns:
The linear growth class.
- static power(exponent: float) GrowthClass#
A space whose extent grows as a user-chosen power of the system size.
- Parameters:
exponent – The exponent to use.
- Returns:
The requested growth class.
- class einsums.graph.IndexSpace#
The semantics of one index space, and nothing else.
Field-wise equality makes a repeated identical registration idempotent and a conflicting one an error. An aggregate for designated initializers; Python uses
make_index_space.- scale_symbol: str#
Letter this space contributes to a symbolic cost polynomial (“o”, “v”, “x”, “g”, …).
- dim_symbol: str#
Name a SYMBOLIC EXTENT over this space goes by (“no”, “nv”, …). Empty when the space has none, and then an axis over it cannot be given a symbolic extent from the space alone.
Distinct from
scale_symbol(the cost-polynomial letter) andname. A ragged space uses"ragged:<space>"instead.
- typical_extent: float#
Advisory extent, used only to break ties when no tensor instance is bound. Zero means unset.
- growth: GrowthClass#
How the extent grows with system size.
- class einsums.graph.InplaceOptimization#
InplaceOptimization pass: in-place storage merging for elementwise consumers.
When an element-aligned elementwise node (DirectProduct, DirectDivision, Axpby with beta == 0, or a member of their grouped forms) pure-overwrites a graph-owned intermediate while reading another graph-owned intermediate for the LAST time, the output reuses the dying input’s storage: the graph metadata merges the two ids (CSE-style rewrite), the output’s lifecycle nodes are dropped, and its executor slot is durably redirected. One buffer allocation and its write-traffic disappear per merge - the CC amplitude-update pattern (R -> Tnew = R * invD) is the canonical win.
This pass is in the default pipeline, run before FreeInsertion / MemoryPlanning so each merge removes a buffer and shortens the intervals those liveness passes then work with.
Soundness guards
Consumer whitelist: only ops whose out[i] depends solely on element i of the inputs may alias output with input (contractions and permutes never qualify). Pure overwrite is detected via the out-tensor-as-input recording convention. A grouped member may only reuse one of its own inputs, and no member of the node may read the destination, because the members run at once.
Both tensors: graph-owned intermediates owning their storage (not views, not redirected onto another tensor, not viewed by anyone), identical dims, dtype and byte size. The source has exactly one producer, which runs before the consumer, and dies at the consumer; the destination has exactly one writer, no Initialize, and no reader ahead of the consumer.
Reads and writes are counted per buffer (Graph::buffer_of), so a node reading a tensor through a redirected slot counts as a reader of the storage the slot was redirected to.
Graphs containing control flow at this level are skipped (bodies reference parent tensors invisibly to plain use-counts); bodies are processed on their own recursion level. GPU-placed graphs are skipped (device shadows swap buffers behind the slots).
num_candidates() still reports the single-producer/single-consumer census this pass exposed when it was analysis-only.
Example (C++)
cg::Graph graph("inplace"); auto &R = graph.scratch<double, 2>("R", n, n); // residual (dies at the update) auto &invD = graph.scratch<double, 2>("invD", n, n); // 1/denominator auto &Tnew = graph.scratch<double, 2>("Tnew", n, n); // amplitude update { cg::CaptureGuard const capture(graph); cg::einsum("ij <- ik ; kj", 0.0, &R, 1.0, A, B); // produce R cg::direct_product(1.0, R, invD, 0.0, &Tnew); // Tnew = R (*) invD, R read last } graph.apply(cg::PassManager::create_default()); // InplaceOptimization runs here // Tnew now reuses R's storage; R's buffer and its write-traffic are gone.Example (Python)
Constructible standalone (getters are properties). A whitelisted elementwise consumer merges; an einsum consumer never does (nothing merges, num_merged stays 0).
import einsums, einsums.graph as cg g = cg.Graph("inplace") R = g.create_zero_tensor("R", [n, n], dtype="float64") invD = g.create_random_tensor("invD", [n, n], dtype="float64") Tnew = g.create_zero_tensor("Tnew", [n, n], dtype="float64") with cg.capture(g): einsums.einsum("ij <- ik ; kj", R, A, B) einsums.linalg.direct_product(1.0, R, invD, 0.0, Tnew) p = cg.InplaceOptimization() pm = cg.PassManager(); pm.add(p); pm.run(g) # or g.apply(cg.default_pass_manager()) # p.num_merged, p.num_candidates (properties, not methods)
Limitations
Only the element-aligned elementwise consumers DirectProduct, DirectDivision and Axpby(beta == 0), and the grouped forms of the three, may alias output with a dying input; contractions (Einsum/Gemm/BatchedGemm) and permutes, grouped or not, are excluded and never merge.
Both tensors must be graph-owned intermediates, non-viewed, with identical dims and byte size; the source needs exactly one producer and this node as its only reader, the destination exactly one writer and a pure overwrite (destination not read).
HOST-only and single-level: any graph with control flow at this level, or with GPU placement / host<->device transfers, is skipped (bodies are handled on their own recursion level).
A destination carrying an Initialize node is skipped rather than merged; the v1 pass does not delete the (now-dead) Initialize.
Future improvements
Handle a destination with an Initialize by deleting the dead init instead of bailing on the merge.
Extend beyond the elementwise whitelist to any consumer whose access is provably element-aligned.
- class einsums.graph.LaplaceTransform#
Substitute a quadrature for a tagged energy denominator and decouple its consumer.
See also
LaplaceTransform.hpp for the mathematics, the tag and every refusal
Added in version 2.0.0.
- add_energy(name: str, vector: Any) None#
Hand the pass one of the orbital-energy vectors the tags name.
Supplied to the PASS rather than found in the graph, which is the shape
MetricFitFactorizationalready has and for the same reason: the energies go into the reciprocal before the capture starts, so no node mentions them and the graph has never seen them. Registering them on the graph instead would leave it holding a handle nothing uses beside the one the setup body captures, two tensors under one name, and a manifest binds by name.The vector becomes an interface tensor of the transformed graph, under this name, because the setup body captures it. That is what lets a saved graph refit its quadrature at a new geometry: a bind moves the energies and the next execute rebuilds the rule.
- Parameters:
name – The name the denominator’s tag uses for this axis.
vector – The energies. Its storage must outlive every replay, since the setup node reads it on each bind.
- Raises:
Exception – When
vectoris not a non-empty rank-1 tensor, or when a different vector is already registered undername.
- add_energy_f32(name: str, vector: Any) None#
The same, for a single-precision problem.
- Parameters:
name – The name the denominator’s tag uses for this axis.
vector – The energies.
- static denominator_tag(energies: list[str], signs: str) ProvenanceTag#
Build the tag a caller puts on a reciprocal denominator.
A helper rather than a documented convention, so the pass reads the attributes out of the same place a caller writes them in.
- Parameters:
energies – One orbital-energy tensor NAME per axis of the denominator, in axis order. Names rather than ids, because they are what a manifest binds by and what lets a saved graph refit at a new geometry.
signs – One character per axis,
'+'or'-', saying whether that axis’s energy enters the denominator added or subtracted.
- Returns:
The tag, ready for
Graph::annotate_tag.- Raises:
Exception – When the two lists differ in length, when either is empty, or when
signsholds a character that is neither'+'nor'-'.
- static error_tensor_name(denominator: str) str#
The tensor a bind’s measured quadrature error is written to.
A function rather than a convention, for the reason
MetricFitFactorization::dropped_param_nameis one: a caller reads the number from the same place the graph writes it. The approximation record carries the error measured at OPTIMIZE time, over the range the energies then had; this is what the range currently bound actually achieves, and the two differ exactly when a rebind widened the interval.- Parameters:
denominator – The tagged tensor’s name.
- Returns:
The name of a one-element tensor the setup body writes on every bind.
- set_epsilon(epsilon: float) None#
The target relative accuracy of the quadrature.
Overrides
einsums:graph:laplace-epsilonfor this pass object, which is the per- pipeline half of the knob convention every rewrite knob here follows.- Parameters:
epsilon – The tolerance. Must be finite and strictly between zero and one.
- Raises:
Exception – When it is not.
- set_points(points: int) None#
Fix the quadrature point count rather than deriving it from the tolerance.
The override exists for reproducing a published number, and it is an override rather than the interface because a count is a means: it says nothing about what the result is worth, and the same count over a wider spectral range is a different approximation.
- Parameters:
points – The count, or zero to go back to deriving it. Must not be one: a trapezoidal rule needs two points or none.
- Raises:
Exception – When
pointsis one or negative.
- num_transformed: int#
How many denominators were replaced by a quadrature on the last run.
(read-only)
- num_numerator_copies: int#
How many numerators the last run took a COPY of rather than dissolving.
One per rewrite whose numerator something else reads. The rewrite needs a numerator whose value it may change, so it copies the definition and leaves the original standing for its other readers; a numerator this product alone holds is dissolved and counts nothing here.
(read-only)
- class einsums.graph.LayoutAssignment#
Choose the storage order of every graph-owned intermediate so contractions read flat.
Example (C++)
cg::Graph graph("layout"); { cg::CaptureGuard const capture(graph); cg::einsum("mbej <- mnef ; njfb", 0.0, &W, 1.0, I, T); cg::einsum("ijab <- imae ; mbej", 1.0, &R, 1.0, T2, W); } cg::PassManager pm; pm.add<cg::passes::LayoutAssignment>(); graph.apply(pm); // W's axes are reordered and both index lists followExample (Python)
import einsums.graph as cg la = cg.LayoutAssignment() pm = cg.PassManager(); pm.add(la); pm.run(g) # la.num_relaid_out -> 1 (getters are properties, not methods)
It also runs as part of
cg.default_pass_manager().Limitations
Candidates are rank-3-and-up graph-owned deferred intermediates only; see the file note for why each half of that is there.
The search is coordinate descent over the layouts some participant asked for, not an exhaustive one over
r! orders per tensor. A layout nobody wants cannot beat one that at least one node does, which is what makes the restriction defensible rather than merely cheap; it is not a proof of optimality, and the pass does not claim one.A
Permuteis folded away only when its copy is one of the decision variables above, which is wherePermuteFusionstill has cases of its own: a rank-two copy, a copy the caller owns, a copy already allocated, and a copy read by something other than a contraction are each pinned here and each still absorbed there. ATransposecarries no descriptor and is rank two by definition, so it is never a candidate.The copy’s source keeps its captured axes, so a chain of two permutes folds neither.
A contraction with a repeated letter in one operand (a diagonal) is not modelled, and pins its tensors.
- num_relaid_out: int#
How many intermediates were given an order other than the captured one.
(read-only)
- num_permutes_folded: int#
How many
Permutenodes the chosen layout turned into identity copies and deleted.(read-only)
- class einsums.graph.LinearCombinationContractionFolding#
Fold transpose-paired contractions into one (the CCSD “2J−K” idiom).
Sibling of
DistributiveFactoring. Where DistributiveFactoring sums different operands sharing the same index pattern, this pass folds contractions that reuse the same operand tensor read with permuted index patterns. Detects groups of einsum nodes that:accumulate into the same output (c_prefactor != 0),
share one operand with an identical index pattern,
read the other operand from the same tensor but with index patterns that are permutations of one another.
Because einsum is linear in each operand, \(\sum_k \alpha_k\,\mathrm{einsum}(\text{spec}_k, A, B) = \mathrm{einsum}(\text{spec}_0, A,\; \sum_k \alpha_k\,P_k(B))\), where \(P_k\) permutes \(B\) into operand-0’s (canonical) layout. The rewrite builds \(L = \sum_k \alpha_k P_k(B)\) once and runs a single contraction: trading \(N\) flop-bound contractions for one contraction plus \(N-1\) cheap memory-bound permute/axpy steps.
Example (CCSD spin-adaptation)
Before:
// Fae[a,e] += 2 * t1[m,f] * ovvv[m,a,f,e] // Fae[a,e] -= 1 * t1[m,f] * ovvv[m,a,e,f]
After:
// L[m,a,f,e] = 2*ovvv[m,a,f,e] - ovvv[m,a,e,f] (permute + axpy) // Fae[a,e] += t1[m,f] * L[m,a,f,e] (single einsum)
In the default pipeline
Registered in
PassManager::create_default, after ElementWiseFusion and BEFORE LoopInvariantHoisting: the fold emits the \(L\) build as its own node whose only input is the paired operand, so when that operand is loop-invariant – the common case, an integral block from one-time setup – hoisting lifts the builder out of the loop and \(L\) is built once instead of every replay. The structural gates below make it a no-op on graphs without the pattern. Add it explicitly only to run it apart from the default pipeline:cg::PassManager pm; pm.add(std::make_shared<LinearCombinationContractionFolding>()); graph.apply(pm);
StreamContractionFusionserves the same 2J-K algebra with a single stream of the shared operand and runs first, consuming the pattern this pass would otherwise fold.Example (Python)
import einsums, einsums.graph as cg g = cg.Graph("lccf") with cg.capture(g): # Same operand tensor B read with permuted index patterns, accumulating into Fae. einsums.einsum("ae <- mf ; mafe", Fae, t1, ovvv, c_pf=0.0, ab_pf=2.0) # seed einsums.einsum("ae <- mf ; maef", Fae, t1, ovvv, c_pf=1.0, ab_pf=-1.0) # accumulate p = cg.LinearCombinationContractionFolding() pm = cg.PassManager(); pm.add(p) g.apply(pm) # p.num_groups -> 1, p.num_eliminated -> 1 (getters are properties, not methods)
Limitations
Members must be einsum nodes with two inputs and one output, sharing one operand (same tensor id and index pattern) and reading the other operand from the same tensor with index patterns that are genuine permutations of one another (at least one member permuted, else it is duplicate-contraction territory, not this pass).
Every non-first member must purely accumulate (c_prefactor == 1) so the reassociation is exact; the first member may seed (overwrite or any prefactor). A stray overwrite in the tail rejects the group.
Conjugated einsums (conj_a/conj_b) are skipped; conjugation is not threaded through the rewrite (they still execute correctly, just unfolded).
Output, shared and non-shared operands must share one dtype; a mixed-dtype triple declines. Each may be a runtime tensor, a typed Tensor<T,Rank> or a view: the \(L\) build and the fused contraction read every operand through its rank-erased geometry, strides included, and the output may be a view the fused contraction writes through.
On a real dtype, every member’s ab_prefactor and node-0’s c_prefactor must be real-valued; complex prefactors fold only on complex dtypes.
Interference guard: between the first and last member, no other node may read/write the output or write the shared / non-shared operand; the fused node occupies node-0’s slot (never appended) to stay scan-before its consumer.
The operand folded into \(L\) must not be a backed tensor SlabStreaming would read a slab at a time (
OptimizerPass::streamed_beside). Building \(L\) holds it whole, and an \(L\) the same size beside it; the members are left for SlabStreaming to stream instead.
Future improvements
Make the fold conj-aware (thread conj_a/conj_b through the \(L\) build) if the conjugated variant shows up hot (see the TODO in the source).
- class einsums.graph.LoopInvariantHoisting#
Loop invariant hoisting: moves body operations whose inputs never change across iterations to run once before the loop.
For each Loop node, identifies body operations whose every input is loop-invariant – not written by any node anywhere in the loop subtree (including nested conditional branches and inner loops), or produced by an already-hoisted node – and lifts them into the enclosing graph, wiring their outputs as inputs of the Loop so the scheduler keeps the writer->reader edge. Invariance is transitive, so a producer chain (T = XᵀH, then F = TX) hoists together. Descent is innermost-first: an invariant lifted from an inner loop into its enclosing body may be lifted again by the outer sweep, one level per composed single-level hoist.
In the default pipeline (populate_default, after ElementWiseFusion). Not in the O1 cleanup cluster of PassManager::create_for.
Example (C++)
cg::Graph graph("lih"); { auto &body = graph.add_loop("loop", niter, [](size_t it) { return it + 1 < niter; }); cg::CaptureGuard const guard(body); cg::einsum("ij <- ki ; kj", 0.0, &T, 1.0, X, H); // X, H never change -> invariant, sole writer of T cg::einsum("ij <- ik ; kj", 0.0, &F, 1.0, T, X); // depends only on invariants -> invariant cg::axpy(1.0, F, &acc); // acc += F changes each iteration -> stays in loop } cg::PassManager pm; pm.add<cg::passes::LoopInvariantHoisting>(); graph.apply(pm); // or PassManager::create_default() // The T- and F-producing einsums now sit before the loop; only the acc update remains in the body.Example (Python)
import einsums, einsums.graph as cg g = cg.Graph("lih") body = g.add_loop("loop", niter, lambda it: it + 1 < niter) with cg.capture(body): einsums.einsum("ij <- ki ; kj", T, X, H) # invariant, sole writer of T einsums.einsum("ij <- ik ; kj", F, T, X) # invariant (transitive) einsums.linalg.axpy(1.0, F, acc) # acc += F varies -> stays in loop lih = cg.LoopInvariantHoisting() pm = cg.PassManager(); pm.add(lih) g.apply(pm) # or cg.default_pass_manager() # lih.num_hoisted -> 2 (getter is a property, not a method)
Limitations
Hoists out of Loop bodies only. Conditional branches are never descended and no node is moved across a branch boundary in either direction (lifting a branch-guarded op would run it unconditionally and change semantics).
Never hoists a self-modifying node: the always-accumulating ops (scale/axpy/axpby/element-transform), any einsum/ permute/batched-gemm with a nonzero destination prefactor, or any node that lists the same tensor as both input and output.
A candidate’s output must have exactly one value-writer in the loop subtree; if another node also writes it, or its single-writer status can’t be proven, the hoist is refused (removing the per-iteration write would change which write wins).
A producer whose output is read by an earlier body node is loop-carried through it and is not hoisted; reads by later body nodes are fine.
A node whose effects its tensor lists do not show (
NodeEffects; acg::customclosure not declared pure) is not hoisted: it may read state the loop changes, or be meant to run once per iteration.A node that reads a parameter or disk dataset another body node writes, or writes one another body node reads or writes, is not hoisted: the order between them travels through that resource, not through a tensor.
No cost model: hoisting a cheap producer of a huge tensor extends that tensor’s live range across the whole loop, which can cost more memory than the recomputation it saves. The pass hoists whenever it is legal, not whenever it is profitable.
Future improvements
Add a cost/benefit test (recomputation cost vs. the extended live range) so a large-tensor producer is hoisted only when it actually pays off, per the caveat in hoist_one_level().
- class einsums.graph.ManifestEntry#
One named slot of a graph’s interface: an operand the graph does not own.
The formalization of the complement of
TensorHandle::is_intermediate. A handle flagged intermediate is storage the graph created for itself and is never an entry here; everything else a node touches is part of the contract a caller has to satisfy, and this says what satisfying it means.Note
dimsholds the extents of the instance the graph was captured at.dim_symbolssays which of them are part of the contract and which a bind may move; an entry with no symbols is fixed at exactlydims, asGraph::rebindalways required.See also
Graph::manifest
See also
Graph::bind
Added in version 2.0.0.
- direction: str#
The direction by name, for Python, where the enum is not bound.
Added in version 2.0.0.
(read-only)
- name: str#
The binding key. Copied from
TensorHandle::name, which capture in turn copied from the tensor. Names are the interface: a saved graph is bound by name, never by id. A tensor registered without a meaningful name of its own (the generated “tensor_<n>” spellings) is a legal entry and a fragile key - it is stable only as long as nothing upstream renumbers, so a graph meant to be saved should name its operands.
- dim_symbols: list[str]#
Per-axis symbolic extent declaration, parallel to
dims, or empty when every axis is literal. An empty string in a populated vector is one literal axis, an ordinary string is a symbol every slot naming it must agree on, and a"ragged:<space>"spelling is an axis whose extent differs per instance.Names, never ids, for the same reason
spacesholds names: this is what a serializer writes and a loader reads back, and a symbol is only meaningful by name.See also
TensorHandle::dim_symbols
See also
Graph::annotate_dims
- class einsums.graph.Materialization#
Materialization pass: give every deferred (shell) tensor a Materialize (and optional Initialize) lifecycle node so it is allocated at the right point during execution.
For each tensor with AllocState::Deferred, this pass:
Finds the earliest node that writes to or reads from the tensor, via the shared UsageAnalysis (a view of a deferred tensor counts as a use of its owner, and a use buried in a loop body / conditional branch surfaces at the enclosing control-flow node’s position).
Inserts a Materialize node just before that point; its executor calls materialize_fn() to allocate the backing storage (for a distributed, non-replicated tensor it first resizes to this rank’s local partition using the DistributionDescriptor that DistributionPlanning attached).
If init_kind is set (Zero, Random), inserts an Initialize node immediately after.
Allocation happens lazily during graph.execute() when the Materialize node runs, NOT during the pass itself. So intermediates only consume memory when needed, MemoryPlanning can see the Materialize nodes for accurate peak estimation, and distributed allocation happens per-rank at execution time. A deferred tensor used inside a loop body or conditional branch has its lifecycle HOISTED into the outermost parent (keyed and deduped by the underlying buffer pointer, so one buffer is materialized + initialized exactly once) and thus runs once per outer execution instead of every iteration / branch entry.
This pass is CORRECTNESS-ENABLING, not an optimization: a graph that uses declare_tensor() / scratch() cannot execute without it, so it is included at every optimization level above O0. It is in the default pipeline, after DistributionPlanning and before SymmetryPropagation / the GPU passes.
Example (C++)
cg::Graph graph("materialization"); auto &tmp = graph.scratch<double, 2>("tmp", n, n); // deferred + intermediate { cg::CaptureGuard const capture(graph); cg::einsum("ij <- ik ; kj", 0.0, &tmp, 1.0, A, B); // tmp = A·B (first use) cg::einsum("ij <- ik ; kj", 0.0, &C, 1.0, tmp, D); // C = tmp·D } graph.apply(cg::PassManager::create_default()); // Materialization runs here graph.execute(); // a Materialize node allocates `tmp` just before the first einsumExample (Python)
Pipeline-internal: the pass is not exposed for standalone construction in Python. Deferred (workspace) tensors are materialized through the default manager.
import einsums, einsums.graph as cg g = cg.Graph("materialization") ws = cg.Workspace("ws") tmp = ws.declare_zero_tensor("tmp", [n, n], "float64") # deferred, zero-initialized with cg.capture(g): einsums.einsum("ij <- ik ; kj", tmp, A, B) einsums.einsum("ij <- ik ; kj", C, tmp, D) g.apply(cg.default_pass_manager()) # materializes + zeroes tmp at first use g.execute()
Limitations
Acts only on tensors in AllocState::Deferred; eager create_tensor() tensors are left untouched.
Allocation is deferred to graph.execute() (the Materialize node’s executor), never performed by the pass itself.
Body-scoped deferred tensors are hoisted to the outermost parent and materialized / initialized once per outer execution; the dedup key is the underlying tensor_ptr, so a null buffer pointer cannot be deduplicated and gets its own lifecycle pair.
Distributed (non-replicated) tensors require their DistributionDescriptor to have been attached already by DistributionPlanning; the Materialize executor resizes to the per-rank local partition.
- __init__() None#
Default-construct.
Reachable from Python, which every other phase-enabling pass already was. This one is correctness-enabling rather than an optimization - a graph using
declare_tensorcannot execute without it - so a caller who wants only that had to run the whole tuning phase to get it, and reach past four scheduling decisions they did not ask for.
- num_loaded: int#
How many of those it filled whole from a backing (see
Graph::annotate_backing).(read-only)
- num_stored: int#
How many tensors produced in memory it stored whole into their write backings.
(read-only)
- class einsums.graph.MemoryPlanning#
MemoryPlanning pass: liveness analysis, memory statistics, and the planned host arena.
Analyzes the graph to determine tensor liveness intervals (from first use to last use) and computes memory statistics for both host and device:
total_memory(): Sum of all tensor sizes (upper bound if all were live simultaneously)
peak_memory(): Maximum sum of simultaneously live tensors at any execution point
device_total_memory(): Sum of all device-resident tensor sizes
device_peak_memory(): Peak simultaneously live device tensors
device_reuse_savings(): Bytes saveable by reusing non-overlapping device allocations
With apply_arena (the default, and the default-pipeline configuration), the liveness intervals are also ACTED on: graph-owned host intermediates whose lifetimes are bracketed by Materialize/Free nodes get first-fit-decreasing offsets in one shared 64-byte-aligned arena per graph, sized to the planned peak. Their Materialize nodes re-attach the tensor at its planned offset (Tensor::materialize_into - no allocation) and their Free nodes detach without freeing, so non-overlapping intermediates share storage and replays touch the same hot pages with zero allocator traffic. Tensors with views, aliases, GPU placement, or unbounded lifetimes are left on their own allocations, as is any graph with a Loop or Conditional at its level (bodies are planned at their own recursion level). A Setup at this level does NOT suppress the plan: only the tensors its body touches are left out, since those are the ones whose lifetime the interval test cannot see.
This pass is in the default pipeline as the LAST pass (with apply_arena defaulting to true, so it both reports statistics and applies the arena). It runs after Materialization / FreeInsertion so the Materialize/Free brackets it plans over already exist.
Example (C++)
cg::Graph graph("memory_planning"); auto &t1 = graph.scratch<double, 2>("t1", n, n); // graph-owned intermediates auto &t2 = graph.scratch<double, 2>("t2", n, n); { cg::CaptureGuard const capture(graph); cg::einsum("ij <- ik ; kj", 0.0, &t1, 1.0, A, B); // t1 lives, then dies cg::einsum("ij <- ik ; kj", 0.0, &t2, 1.0, t1, D); // t2 can reuse t1's arena slot } graph.apply(cg::PassManager::create_default()); // MemoryPlanning (arena) runs last // Non-overlapping intermediates now share one arena block; peak_memory() < total_memory().Example (Python)
Constructible standalone for analysis (getters are properties). Applied on its own it only reports, because the Materialize/Free brackets it packs are placed by earlier pipeline passes.
import einsums, einsums.graph as cg g = cg.Graph("memory_planning") with cg.capture(g): einsums.einsum("ij <- ik ; kj", C, A, B) p = cg.MemoryPlanning() pm = cg.PassManager(); pm.add(p); pm.run(g) # or g.apply(cg.default_pass_manager()) # p.total_memory, p.peak_memory, p.num_planned, p.planned_arena_bytes (properties, not methods)
Limitations
Arena planning is HOST-only and skips any graph that has a Loop or Conditional at its level, or any GPU / host<->device transfer node; those graphs get statistics only. A Setup node costs only the tensors its body reaches (
EscapeAnalysis::touched_by_subtree), plus any tensor with no attached pointer, which that query cannot answer for.Only graph-owned is_intermediate tensors bracketed by exactly one Materialize and one Free node, not viewed or aliased, with materialize_into_fn + release_fn and nonzero bytes, are arena-placed.
The interval test uses body-LOCAL node positions and is blind to cross-iteration (loop-carried) liveness; today no in-body Materialize/Free bracket is ever reachable and a wraparound canary fires if FreeInsertion ever places one.
Reported cross-loop peak is a max over graphs (a defensible lower bound), not a precise loop-carried peak; device statistics are reporting-only (no device arena is applied, and device_peak_memory / device_reuse_savings are not exposed to Python).
Future improvements
Precise loop-carried liveness for an exact cross-loop peak (and to unlock arena planning inside loop bodies by treating iteration-crossing tensors as always-live).
A device-side arena that acts on device_reuse_savings the way the host arena acts on peak_memory.
- planned_tensor_bytes: int#
Sum of the planned tensors’ own buffer sizes (>= planned_arena_bytes; the difference is the storage sharing the plan achieves).
(read-only)
- managed_peak_memory: int#
The most a replay holds of the tensors the graph allocates and frees, plus an applied arena: the quantity Graph::last_run reports as peak_bytes, predicted from the lifecycle nodes in the order a replay runs them.
peak_memoryalso counts the caller’s tensors and assumes every tensor freed after its last use; this one counts what the replay does.Added in version 2.0.0.
(read-only)
- resident_memory: int#
What a replay holds from its start to its end outside
managed_peak_memory: the caller’s tensors and any intermediate given storage outside a lifecycle node, as Graph::last_run reports it in resident_bytes. The program holds the two together at its peak, and that sum is what has to fit –einsums:max-memory.Added in version 2.0.0.
(read-only)
- class einsums.graph.MetricFitFactorization#
Offer a four-index tensor as a metric-fitted product of one three-index factor.
See also
MetricFitFactorization.hpp for the mathematics and for what chemistry calls it
Added in version 2.0.0.
- __init__(tag: str, three_index: Any, metric: Any, bound: float, drop_threshold: float = einsums::compute_graph::MetricFitFactorization::default_drop_threshold, name: str = "MetricFit") None#
The same, taking runtime-rank tensors. This is the overload Python gets.
A view converts from a
RuntimeTensorin C++, carrying its name, but the bindings will not make that conversion on their own, so the type a Python caller actually holds needs an overload of its own.Note
The drop-threshold default is spelled with its class qualifier because the binding generator copies a default argument through verbatim, and an unqualified class-scope constant does not resolve where the generated code spells it.
- static dropped_param_name(provider: str, tensor: str) str#
The parameter a fitted graph reports its dropped auxiliary directions under.
A function rather than a documented convention, so a caller reads the name from the same place the graph writes it. Zero means the metric was well conditioned and the fit kept every direction the caller supplied; anything else is accuracy lost in a way the asserted bound does not describe.
- Parameters:
provider – The provider’s
name.tensor – The tagged tensor’s name.
- Returns:
The key to read out of the graph’s parameter table after an execute.
- class einsums.graph.MultiTermFactorization#
Jointly choose contraction orders and shared intermediates over one region.
Example (C++)
cg::Graph graph("mtf"); { cg::CaptureGuard const capture(graph); cg::einsum("i,l <- i,k ; k,l", 0.0, &T1, 1.0, A, B); // whatever order the author wrote cg::einsum("i,j <- i,l ; l,j", 0.0, &R1, 1.0, T1, C); cg::einsum("k,j <- k,l ; l,j", 0.0, &T2, 1.0, B, D); // the other bracketing cg::einsum("i,j <- i,k ; k,j", 0.0, &R2, 1.0, A, T2); } cg::PassManager pm; auto pass = std::make_shared<cg::passes::MultiTermFactorization>(); pass->set_search_enabled(true); // or set einsums:graph:structural-search pm.add(pass); graph.apply(pm); // Both terms now read one shared (A B), and T2 is gone.Example (Python)
import einsums.graph as cg mtf = cg.MultiTermFactorization() mtf.set_search_enabled(True) pm = cg.PassManager(); pm.add(mtf); pm.add(cg.Materialization()); pm.run(g) # mtf.num_shared -> 1 (getters are properties, not methods)
Limitations
A term’s factors are flattened out of the captured chain only through intermediates the region can dissolve: written once, overwritten rather than accumulated, carrying a product prefactor of one, and reading nothing a statement in between overwrites. Anything else stays a factor in its own right, which is correct but hides the products inside it from the search.
A definition several statements consume is inlined into each consumer whose bracketing it improves and KEPT for the rest, which is why a consumer that gains nothing costs nothing. The definition is dissolved only when every consumer took it. At most
max_readersconsumers are considered; a definition more of them read is left whole with the reason.Three node kinds present the product the flattener reads: a contraction, a
OpKind::DirectProduct(the same product with no summed letter) and aOpKind::Dot(the same product summed over every letter). An amplitude formed by a contraction, scaled by a direct product and reduced by a dot is therefore one product rather than a stored leaf every candidate has to rebuild.Shared occurrences must be in DIFFERENT terms. Two occurrences of one pair inside one term would have to be applied together under a disjointness check, since applying one moves the other’s factor positions and the two may name a factor in common.
Factors are capped at
max_factors, because the per-term program is exponential in that number and a cap is the honest way to bound it. The cap is a property of the program a caller brings rather than of the pass, so it comes fromeinsums:graph:factorization-max-factorsunlessset_max_factorsoverrides it here.A factor that repeats an index letter is a diagonal access, whose cost this pass does not model; such a term is declined.
Shared candidates are pairs. See the file note for what that does and does not reach.
A candidate that would leave a term with a single factor is declined: the result would be a copy rather than a contraction, which is CSE’s business and not a shape this emits.
- set_search_enabled(on: bool) None#
Run the search on this pipeline whatever
einsums:graph:structural-searchsays.The programmatic half of the option, and it exists for the reason
PassManager::enabledoes: a driver that had only the option would have to mutate process-global configuration to exercise one pipeline, which also makes it unrunnable concurrently. An explicit setting wins over the option in both directions.- Parameters:
on – Whether to search.
- set_max_factors(cap: int) None#
Set the factor cap for this pipeline, overriding the option.
- Parameters:
cap – The new cap, clamped to at least two.
- set_max_readers(cap: int) None#
Set the consumer cap for this pipeline, overriding the option.
- Parameters:
cap – The new cap, clamped to at least one.
- set_cache_enabled(on: bool) None#
Keep and replay plans on this pipeline whatever
einsums:graph:factorization-cachesays.The programmatic half of the option, for the reason
set_search_enabledis: a driver that had only the option would have to mutate process-global configuration to exercise one pipeline. An explicit setting wins over the option in both directions, and switching the cache off does not discard what it already holds;clear_cachedoes that.- Parameters:
on – Whether to cache.
- clear_cache() None#
Forget every plan this pass has kept.
The explicit clear the cache is specified to have. Nothing invalidates an entry on its own, because nothing can: an entry is keyed on the content hash of the graph that produced it, so a changed graph misses rather than reading a stale plan.
- search_enabled: bool#
Whether the search will run, taking the explicit setting over the option.
(read-only)
- max_factors: int#
The largest number of factors a term may have before it is declined.
Taken from
einsums:graph:factorization-max-factorsunlessset_max_factorshas stated one for this pipeline, which is the same two-level shapesearch_enabledhas and exists for the same reason: a driver that had only the option would have to mutate process-global configuration to exercise one pipeline.(read-only)
- max_readers: int#
How many consumers a definition may be inlined into before it is left whole.
The bound on the other direction the search grows in. A definition several statements read is inlined into each of them that profits and kept for the rest, so a definition with
kconsumers costs at mostkterms and each of them is capped bymax_factorson its own. Taken fromeinsums:graph:factorization-max-readersunlessset_max_readershas stated one for this pipeline.(read-only)
How many intermediates it introduced for more than one term to share.
(read-only)
- cache_enabled: bool#
Whether plans will be kept, taking the explicit setting over the option.
(read-only)
- num_cache_misses: int#
How many regions searched because no plan was held for them, this apply.
(read-only)
- was_cut_off: bool#
Whether the last run stopped because its wall-clock allowance ran out.
A report that could not distinguish this from “the graph was already optimal” would be useless in exactly the case a budget exists for, so the pass says which one happened.
What a cut-off means for the emitted graph
The tree the pass emits becomes a function of how fast the machine is, because the search keeps the best candidate it had reached rather than the best one there is. That costs optimization and not correctness, and a partial plan is never cached, so nothing durable carries the machine in it. A caller that needs the SAME graph out of two runs, a test asserting a shape above all, therefore has to take the allowance away rather than make it generous:
PassManager::set_optimizer_budget(0), which wins overeinsums:graph:optimizer-budget, and this getter is then what says the removal took. A generous allowance only moves the point at which the machine decides the answer.(read-only)
- class einsums.graph.NaryEinsumStep#
One contraction of an
plan_nary_einsumplan.Operands are numbered as the spec names them, from zero, and the result of step
kis operandn + kfor a spec overnoperands. The last step writes the einsum’s output.Added in version 2.0.0.
- class einsums.graph.NaturalAuxiliaryFactorization#
Offer a three-index tensor over a truncated auxiliary index.
See also
NaturalAuxiliaryFactorization.hpp for the mathematics and for what chemistry calls it
Added in version 2.0.0.
- __init__(tag: str, three_index: Any, threshold: float = 0., name: str = 'NaturalAuxiliary') None#
Construct the provider.
Why the threshold is relative where the metric fit’s is absolute
The two guards are applied in different places. A metric fit’s runs inside a captured element operation, whose policy number is bound when its executor is built, so a relative cutoff there would need a reduction feeding a value into a guard; that is the mechanism
MetricFitFactorizationrecords as one to add. This one runs in ordinary code, at propose time, over eigenvalues held in a local buffer, so comparing against the largest of them costs nothing and the conventional relative cutoff is simply available.- Parameters:
tag – The provenance tag this claims, e.g.
"eri".three_index –
B[Q,m,n], which is also the tensor the caller tags. Checked against the tagged handle’s buffer inpropose, so a caller who hands over a different tensor gets a decline rather than a truncation of something else.threshold – Auxiliary directions whose singular value is at or below this fraction of the largest are dropped, or zero to take
einsums:graph:naf-threshold.name – The provider’s name, which the approximation record and the report carry.
- Raises:
Exception – When
thresholdis not finite, is negative, or is at least one. One would drop every direction but the first, which is a decomposition of nothing, and there is nothing a negative threshold could mean.
- report_dropped_into(dropped: Any) None#
Where the truncation writes what it threw away on this bind.
The caller’s own tensor, for the reason a grid fit’s residual destination is one: a measurement a caller cannot read is a measurement nobody makes. The record points at it by name, so a caller holding a record knows which of their tensors to look in.
Without it the fitting emits no measurement nodes and the record carries the number measured at optimize time alone, which is what the structure claims rather than what this bind found.
- Parameters:
dropped – A rank-1 tensor the fitting writes the norm of the dropped singular values, relative to the norm of all of them, into.
- static register_naf_space(graph: Graph, outer: str = 'aux', fraction: float = 0.5) SpaceId#
Register the truncated auxiliary space in
graph'sown registry.A space is a statement about a graph rather than about a provider, and
proposeis handed a const graph precisely so a provider cannot make one. So a caller registers it, and this is the one call that does: idempotent for a repeated identical declaration, asSpaceRegistry::register_spaceis.It also DECLARES the two relations that make the truncation reasonable to a pass, when the registry already holds the space they relate to: the truncated space is contained in
outerand its scale is smaller. Containment is what says a contraction over the truncated axis is a restriction of the one over the full axis rather than an unrelated quantity, and the scale order is what lets the cost comparison rank the two forms without falling through to its arbitrary tie-break. Declared rather than inferred, which is the registry’s own rule; whenouteris not registered, neither relation is stated and the comparison is weaker rather than wrong.The typical extent is DERIVED from
outer's, atfractionof it, rather than left unstated the way a grid’s is. A grid has no relation to the basis and a truncated auxiliary index is a fixed fraction of the auxiliary set by construction, so the fraction is the method’s own claim about itself. It is also what the cost comparison requires: its second rung ranks a polynomial it cannot substitute below one it can, so a truncated form carrying a space with no typical extent is declined for being unmeasurable rather than for being expensive, which is the shape of a decline this call exists to prevent.Register
outerBEFORE calling this, since the extent is read from it here andSpaceRegistry::register_spaceis idempotent only for an identical redeclaration.- Parameters:
graph – The graph whose registry gains the space.
outer – The name of the space the auxiliary axis of the untruncated tensor carries, or empty to declare no relation and no extent.
fraction – What fraction of
outer'stypical extent the truncated space is expected to be. The published measurements for natural auxiliary functions put it at about a half, which is the default.
- Returns:
The space’s id in that registry.
- Raises:
Exception – When
fractiondoes not lie strictly between zero and one.
- static keep_matrix_name(provider: str, tensor: str) str#
The name the rectangular truncation matrix is bound under.
A constant of the structure rather than of the problem: it is the leading columns of an identity matrix, and the fitting contracts the eigenvectors against it because the node set has no reconstructible slice. A caller rebinding a saved graph supplies it under this name, the way they supply a collocation matrix.
- Parameters:
provider – The provider’s
name.tensor – The tagged tensor’s name.
- Returns:
The interface name.
- threshold: float#
The relative singular-value cutoff, taking the constructor over the option.
(read-only)
- class einsums.graph.NodeRun#
One node’s share of a replay.
A node in a loop body ran once per iteration:
msis the sum andrunsthe count. A control-flow node’s own time includes its body’s, whose nodes have entries of their own.Added in version 2.0.0.
- class einsums.graph.NodeTiming#
Per-node timing entry.
- class einsums.graph.OpenMPExecutor#
OpenMP task-based executor, launches independent nodes in parallel.
Uses OpenMP tasks with dependency tracking. When a node completes, it decrements the in-degree of its successors. Successors whose in-degree reaches zero are launched as new tasks.
Note
BLAS calls within nodes may use their own OpenMP parallelism. For small graphs, the sequential executor may be faster due to reduced thread management overhead.
- class einsums.graph.OptimizerPass#
Abstract base class for optimization passes over a computation graph.
An optimization pass inspects a Graph’s node list and may modify it to improve performance. Passes can fuse operations, eliminate redundancies, reorder nodes for better memory behavior, or analyze the graph and report recommendations.
Implementing a custom pass
class MyPass : public OptimizerPass { public: std::string name() const override { return "MyPass"; } protected: bool transform(Graph &graph) override { // Inspect and modify graph.nodes() return false; } };A pass implements
transformand is run throughrun, which records the change on the graph for a later save to read.Note
Passes that modify the graph should call graph.mark_sorted() if they produce a valid topological ordering, to prevent unnecessary re-sorting.
- set_verbosity(level: int) None#
Set the pass’s introspection verbosity.
Levels: 0 = silent (default), 1 = summary (aggregate effect), 2 = detail (each modification applied), 3 = trace (each candidate examined, including why it was rejected). Output goes to the passes logger, prefixed with the pass name: standard error unless
--einsums:log:destinationsays otherwise, at any log level. Usually set in bulk viaPassManager::set_verbosityrather than per pass.From level 2 up,
PassManager::explain()also grows a “not applied” section built fromskip_reasons- the aggregated form of what level 3 narrates per candidate. Reach for that first when a pipeline looks inert: the tally names the gate, and is a returned string rather than narration you have to read past.
- name: str#
Human-readable pass name, exposed so Python tests can assert which pass they’re invoking.
(read-only)
- decisions: list[Decision]#
Everything this pass did, declined and reported on its last apply, as records.
The reader’s counterpart of
explainandskip_reasons, which print from the same calls: match a decision’sDecision::coderather than its words.Added in version 2.0.0.
(read-only)
- skip_reasons: list[tuple[str, int]]#
Why this pass declined the candidates it looked at.
One entry per distinct reason, with the number of candidates that hit it, ordered most-frequent first. Populated by
note_skipduringtransform(); empty for a pass that never declines anything or has not been taught to explain itself yet.This is the negative half of
explain: explain() says what a pass DID, skip_reasons() says what it declined and why. A pipeline that looks inert usually has a full skip tally - that is the useful signal, and reading it should not require rebuilding with a debugger attached.Exposed because “reading it should not require a debugger” is a claim about every language the library is used from, and the passes whose whole behaviour is a list of refusals are the ones a caller most needs it for. The report
PassManager::explainbuilds carries the REGION-level declines only, so a per-candidate reason is otherwise reachable from C++ and nowhere else.(read-only)
- class einsums.graph.PassManager#
Manages an ordered sequence of optimization passes.
The PassManager collects passes and runs them in order on a graph. Use add() to append individual passes, or use create_default() to get a PassManager pre-loaded with all built-in passes in the recommended order.
Example: custom pass pipeline
cg::PassManager pm; pm.add<cg::passes::ConstantFolding>(); pm.add<cg::passes::ScaleAbsorption>(); pm.add<cg::passes::CSE>(); pm.add<cg::passes::Reorder>(); graph.apply(pm);
Example: default pass pipeline
auto pm = cg::PassManager::create_default(); graph.apply(pm);
See also
Graph::apply(PassManager&)
See also
Pipeline::apply(PassManager&)
See also
create_for(OptLevel)
- __init__() None#
Default-construct an empty PassManager. Explicit (rather than implicit) so the binding codegen has a constructor declaration to annotate with APIARY_EXPOSE.
- add(optimizer_pass: OptimizerPass) PassManager#
Non-templated overload taking shared ownership of a pass.
Exists so the Python binding can write
pm.add(cg.CSE()): the templated form can’t be bound directly because pybind11 has no way to deducePassTypefrom a Python call site. C++ callers should preferadd<PassType>(...)since it constructs in place. Stored asshared_ptrto match the pybind11 holder type, pybind can’t transfer ownership of a Python-heldunique_ptracross the FFI boundary withoutpy::smart_holder.
- disable(pass_name: str) PassManager#
Switch one pass off by name, without removing it from the pipeline.
The programmatic half of
einsums:pass:disable. Both exist because they answer to different people: the option is what a user reaches for from a command line with no rebuild, and this is what a driver reaches for when it has to run the same pipeline N times with a different pass switched off each time. A driver that had only the option would have to mutate process-global configuration to do its job.The name is the pass’s
OptimizerPass::name, and it need not be in the pipeline yet: switches are consulted atrun, so disabling beforepopulate_defaultworks. A name that still matches no pass whenrun()finishes is REPORTED throughexplainrather than ignored - a mistyped pass name that silently does nothing is the failure mode this whole surface exists to avoid.pm.disable("CSE").disable("Reorder");Added in version 2.0.0.
- Parameters:
pass_name – The pass to switch off.
- Returns:
Reference to this PassManager, for chaining.
- enable(pass_name: str) PassManager#
Switch one pass back on, overriding
einsums:pass:disable.Undoes a
disable, and also overrides the option: an explicit call here beats an environment variable, because the more specific statement about this pipeline should win, and a program that asked for a pass by name and silently did not get it is the surprise this surface is meant to remove.Added in version 2.0.0.
- Parameters:
pass_name – The pass to switch on.
- Returns:
Reference to this PassManager, for chaining.
- disabled_passes() list[str]#
The passes the last
runactually skipped, in pipeline order.Empty before the first run, and empty on a run that skipped nothing. Reports what HAPPENED rather than what was requested, so a name in
einsums:pass:disablethat matched no pass does not appear here; seeunmatched_switchesfor those.Added in version 2.0.0.
- Returns:
The skipped passes’ names.
- unmatched_switches() list[str]#
Switch names, from either source, that matched no pass in the pipeline.
A mistyped name is indistinguishable from a correctly typed one for a pass this build does not have, and both produce a pipeline that quietly did not do what was asked. Sorted, so the report is diffable.
Added in version 2.0.0.
- Returns:
The unmatched names.
- set_verbosity(level: int) None#
Set introspection verbosity for every pass in the pipeline.
Propagates
levelto all currently-registered passes and to any added afterward, and makesrun()print a per-pass summary line (name: MODIFIED N -> M nodes (T ms)) to the passes logger. SeeOptimizerPass::set_verbosityfor the level meanings.pm = cg.default_pass_manager() pm.set_verbosity(2) # narrate each modification g.apply(pm)
- set_optimizer_budget(allowance_ms: int) None#
Give every pass in this pipeline a wall-clock allowance for its run.
The programmatic half of
einsums:graph:optimizer-budget, and it exists for the same reasondisabledoes: a driver that wanted to bound one pipeline would otherwise have to mutate process-global configuration to do it, which also makes it unrunnable concurrently. An explicit setting wins over the option, because the more specific statement about this pipeline is the one that should.- Parameters:
allowance_ms – How long each pass may take, in milliseconds. Zero or negative means unlimited.
- run(graph: Graph) bool#
Run all passes in order on the given graph.
- Parameters:
graph – The graph to optimize.
- Returns:
True if any pass modified the graph.
- explain() str#
One human-readable report of what the last run() did.
Harvests the per-pass statistics (nodes eliminated, chains restructured with estimated speedups, buffers merged in place, Frees inserted, arena size vs the buffers it hosts, batches formed and profitability-gate skips) into a few lines of text. Empty until run() has been called. See Graph::explain() for the graph-level entry point.
At verbosity >= 2 the report gains a “not applied” section listing, per pass, how many candidates it declined and why (see
OptimizerPass::skip_reasons). “(no optimizations applied)” on its own cannot tell you whether the graph was already optimal or whether every candidate hit one satisfiable gate - and those call for opposite responses - so raise the verbosity before concluding a pipeline is inert.Each line is prefixed with the reporting pass’s
PassPhase, because “which phase produced this” is the first question asked of a rewrite that turns out to be wrong on one machine and right on another.
- populate_default() None#
Populate this PassManager with the default pass list (in place).
Equivalent to
*this = create_default()but doesn’t require the class to be move-assignable. Used by the Python binding, which can’t bindadd<PassType>()(templated) and so needs an instance method to put the canonical pass list together.
- populate_analysis() None#
Append the read-only passes. @see analysis_pass_manager
Added in version 2.0.0.
- populate_structural() None#
Append the machine-independent rewrites. @see structural_pass_manager
Added in version 2.0.0.
- populate_resource() None#
Append the machine-dependent node-set changes. @see resource_pass_manager
Added in version 2.0.0.
- class einsums.graph.PermuteFusion#
Permute-into-einsum fusion: absorbs an axis-reordering Permute into the subscript of the Einsum that reads it.
Eliminates one tensor-shaped data copy (and, on GPU, one kernel launch + device round-trip) per match by rewriting the consumer einsum to index the pre-permute tensor directly. The rewrite mutates
EinsumIndicesin place (captured by the executor via shared_ptr, so it takes effect on the next graph.execute() without rebuilding the lambda), updates theEinsumDescriptor::specsnapshot so analysis passes stay consistent, redirects the permute-output slot at the source tensor’s storage, and removes the Permute node.In the default pipeline (populate_default; also the O1 cleanup cluster in PassManager::create_for). Ordered BEFORE CSE/DNE so duplicate permute->einsum patterns collapse into the same fused node, and before Materialization / GPU placement so those passes never allocate or place a tensor that is about to be removed.
Example (C++)
cg::Graph graph("permute_fusion"); { cg::CaptureGuard const capture(graph); cg::permute("ji <- ij", &A_T, A); // physical transpose cg::einsum("ik <- ji ; jk", 0.0, &C, 1.0, A_T, B); // GEMM on the transposed copy } cg::PassManager pm; pm.add<cg::passes::PermuteFusion>(); graph.apply(pm); // or PassManager::create_default() // The permute is gone; the einsum now reads A directly with subscript "ij" on the A slot.Example (Python)
import einsums, einsums.graph as cg import einsums._core.graph as _G g = cg.Graph("permute_fusion") with cg.capture(g): einsums.permute("ji <- ij", A_T, A) # physical transpose einsums.einsum("ik <- ji ; jk", C, A_T, B) # GEMM on the transposed copy pf = _G.PermuteFusion() pm = _G.PassManager(); pm.add(pf); pm.run(g) # pf.num_rewrites -> 1 (getter is a property, not a method)
It also runs as part of
cg.default_pass_manager().Limitations
The consumer must be an Einsum node and the permuted tensor must feed one of its first two operand slots (A or B); a permute feeding a third-or-later operand, or any non-einsum consumer, is not fused.
The Permute must be a pure axis reordering: alpha == 1 && beta == 0 (the live values), no permutation operator, with c_indices a duplicate-free permutation of a_indices. Scaling, accumulation, an antisymmetrizer, or diagonal/sum index patterns disqualify it.
The Permute’s output must have exactly one consumer; a shared transposed temporary is left in place.
The Permute’s output must be a graph-owned intermediate that no child sub-graph references. Fusing removes the only write to it, so a tensor the caller holds, or one a loop body reads, keeps its permute.
The consumer einsum must carry populated EinsumDescriptor::indices shared state (the mutable-indices infrastructure); an einsum without it, or a slot whose rank disagrees with the permute output rank, is skipped defensively.
The producer kind must be Permute; the fusion never introduces a permute, only removes one.
What this still owns after ``LayoutAssignment``
LayoutAssignmentdeletes a permute by choosing its output’s storage order so the copy becomes an identity, which reaches the shared-temporary case this pass declines. It does not replace this one. Two shapes are fused here and pinned there, each because the layout pass only ever moves a tensor it could equally have declared differently in the first place: a rank-two copy (a layout decision variable is rank three and up, since BLAS reads a matrix either way through transa), and a copy whose storage is already allocated rather than a deferred declaration. A chain of two permutes is likewise fused here one link at a time and folded there not at all, since the layout pass pins a permute’s source.Future improvements
Extend fusion to non-einsum consumers (e.g. gemm/BatchedGemm slots) and to permutes feeding operand positions beyond A/B.
Handle a permute with multiple consumers by fusing into each reader instead of bailing on the shared-temporary case.
- class einsums.graph.Pipeline#
A pipeline of sequential stages with optional iterative loops.
Pipeline models real computational workflows as a linear sequence of stages, where each stage is either:
A one-shot subgraph (e.g., setup, post-processing)
An iterative loop with convergence check (e.g., SCF iterations)
Intermediate tensors shared across stages should be declared in the outer scope so they outlive the pipeline.
Example: SCF-like workflow
// Intermediates in outer scope auto tmp = create_zero_tensor<double>("tmp", N, N); cg::Pipeline pipeline("scf"); // Stage 1: Setup { auto &setup = pipeline.add_stage("setup"); cg::CaptureGuard guard(setup); cg::einsum(...); // Initialize } // Stage 2: Iterative loop { auto &loop = pipeline.add_loop("scf_iter", 200, [&](size_t iter) { return !converged(); }); cg::CaptureGuard guard(loop); cg::einsum(...); // SCF step } // Stage 3: Post-processing { auto &post = pipeline.add_stage("post"); cg::CaptureGuard guard(post); cg::einsum(...); // Final computation } // Optimize and run cg::passes::ScaleAbsorption fuse; pipeline.apply(pm); pipeline.execute();See also
Graph for individual stage graphs
See also
LoopNode for iterative stage configuration
- __init__(name: str) None#
Construct a pipeline with the given name.
- Parameters:
name – Human-readable name for profiling and debugging.
- add_stage(name: str) Graph#
Add a one-shot (non-looping) stage to the pipeline.
Returns a reference to the stage’s Graph for use with CaptureGuard. Stages execute in the order they are added.
The reference stays valid for the life of the pipeline, including across later add_stage() and add_loop() calls, so a caller may hold several at once and revisit an earlier stage.
- Parameters:
name – Human-readable name for the stage.
- Returns:
Reference to the stage’s Graph.
- add_loop(name: str, max_iterations: int, condition: Any) Graph#
Add an iterative loop stage to the pipeline.
Returns a reference to the loop body’s Graph for use with CaptureGuard. The loop executes the body repeatedly until the condition returns false or max_iterations is reached.
- Parameters:
name – Human-readable name for the loop stage.
max_iterations – Maximum number of iterations (safety limit).
condition – Predicate called after each iteration. Return false to stop.
- Returns:
Reference to the loop body’s Graph.
- apply(pm: PassManager) bool#
Apply a PassManager to all stages.
Runs all passes on each one-shot stage’s Graph and each loop stage’s body Graph. Returns true if any stage was modified.
auto pm = cg::PassManager::create_default(); pipeline.apply(pm);
- class einsums.graph.ProvenancePropagation#
Propagate provenance tags across identity-preserving operations.
An analysis pass: it writes annotations and never touches the node set. See the file comment for exactly which operations propagate and why a view is not one of them.
- class einsums.graph.ProvenanceTag#
What a tensor is, for a pass that has to recognize it rather than merely size it.
A
namefrom an open vocabulary, plus optional key/value attributes for anything the name alone cannot carry (which basis a set of integrals is over, which order a denominator is). Attributes are kept SORTED by key, so two tags built in different orders compare equal and a saved graph’s bytes do not depend on the order a caller happened to set them in.See also
TensorHandle::tag
- static make(name: str) ProvenanceTag#
Build a tag carrying just a vocabulary name.
A factory rather than a constructor, and the reason is that this type is an AGGREGATE: C++ code writes
ProvenanceTag{.name = "eri"}, and any user-declared constructor would end that. Python needs some way to make one, since the binding generator gives an exposed aggregate no constructor at all and the type was reachable but unbuildable.- Parameters:
name – The vocabulary name.
- Returns:
The tag.
- static make_with_attributes(name: str, attributes: list[tuple[str, str]]) ProvenanceTag#
Build a tag with attributes.
A separate name rather than a defaulted argument on
make, because the generator copies a default argument through verbatim and a braced empty one does not compile.- Parameters:
name – The vocabulary name.
attributes – Key/value qualifications.
- Returns:
The tag.
- class einsums.graph.RegionIdentity#
Raise every region and lower it unchanged.
The framework’s own test, in pass form, and the gate everything else rests on: raising an expression and lowering it must produce a graph that computes bit-for-bit what the original did. Nothing about that is guaranteed by construction. Lowering rebuilds each node from the algebra rather than reusing what it raised, so anything the IR fails to carry - a conjugation flag, a destination prefactor, an index list a pass had rewritten through the live block - comes back as a different number rather than as a missing field nobody notices.
It is a pass rather than a test helper so the differential fuzz corpus can drive it: the corpus is where the shapes this would otherwise never see live. Not in
PassManager::create_default, because rewriting nothing is not an optimization; it is registered where the fuzzers can reach it.
- class einsums.graph.RegionRewrite#
Base class for a pass that rewrites regions through
TensorExpr.Derive and override
rewrite. Everything else - forming regions, raising, lowering, skip reasons, the before/after dump, the statisticsexplainreadscomes from here.
Exposed to Python despite being abstract, as
OptimizerPassis and for the same reason: the binding for a concrete pass needs its DIRECT base to be a bound type, or the generated class has no inheritance chain andPassManager.addrefuses it as an unrelated type. Nothing constructs one.- set_dump(on: bool) None#
Collect the before/after dumps regardless of the option.
- Parameters:
on – Whether to collect.
- set_verify_costs(on: bool) None#
Check every accepted rewrite’s reported cost against the NODES, off by default.
The cost line is what a report offers as evidence a rewrite paid, and it is derived from the algebra alone: a term the rewrite built carries whatever cost the client gave it, and nothing compared that to the nodes the lowering then emitted. The after side read zero on every rewrite MultiTermFactorization had ever made, for exactly that reason, and went unread until a case asked whether a loop space had really left.
With this on, the before side is checked against the flops of the region’s own nodes and the after side against the flops of the nodes the lowering emitted, both through
symbolic_cost_for. Two derivations of one number, which is what makes either of them evidence. Off by default because it walks the node set once per rewrite and a pipeline in the default manager should not pay for a self-check.- Parameters:
on – Whether to check.
- class einsums.graph.Reorder#
Memory-aware topological sort: reschedules independent nodes so the ones that free the most memory run earliest.
Re-sorts the node list with a priority-based Kahn’s algorithm. The dependency graph encodes all three hazard classes – RAW (writer->reader), WAW (writer->writer), and WAR (reader->writer) – over each node’s effective I/O (so a Loop/Conditional carries edges for the tensors its body touches) with view aliases resolved to the owning buffer, so only genuinely independent nodes may swap. Among the ready set, a max-heap picks the node with the highest net score: the bytes of the tensors it is the last user of, less the bytes of those it is the first user of, counting only tensors the graph frees (intermediates and graph-owned read-backed tensors). Equal scores keep program order. The reschedule is kept only if its peak, with each such tensor live from its first use to its last, is lower than the given order’s. The pass moves nodes only; it never adds, removes, or rewrites them.
In the default pipeline (populate_default, after GEMMBatching so the scheduler sees a batched node as one unit). Not in the O1 cleanup cluster of PassManager::create_for.
Example (C++)
cg::Graph graph("reorder"); { cg::CaptureGuard const capture(graph); cg::einsum("ij <- ik ; kj", 0.0, &Big, 1.0, A, B); // large intermediate cg::einsum("pq <- pr ; rq", 0.0, &Small, 1.0, X, Y); // independent, small cg::einsum("i <- ij", 0.0, &r, 1.0, Big); // last consumer of Big -> frees it } cg::PassManager pm; pm.add<cg::passes::Reorder>(); graph.apply(pm); // or PassManager::create_default() // Among ready nodes the reducer over Big is scheduled early so Big is freed before Small's chain grows the footprint.Example (Python)
import einsums, einsums.graph as cg g = cg.Graph("reorder") with cg.capture(g): einsums.einsum("ij <- ik ; kj", Big, A, B) einsums.einsum("pq <- pr ; rq", Small, X, Y) einsums.einsum("i <- ij", r, Big) pm = cg.PassManager(); pm.add(cg.Reorder()) g.apply(pm) # or cg.default_pass_manager() # Reorder exposes no result counter; it only permutes the node order to lower peak memory.
Limitations
It reschedules only: it never fuses, splits, or eliminates nodes, and it cannot lower peak memory below what the fixed node set and its true dependencies allow.
The net-score ranking is a greedy local heuristic, not a globally optimal peak-memory schedule. The peak check only guarantees it is never worse than the order given.
The peak it compares is a model: it ignores FreeInsertion’s size floor, so a tensor below it counts as freed here but stays allocated at run time.
If the dependency graph is cyclic or otherwise leaves nodes unscheduled (order.size() != n), the pass bails and leaves the node order untouched.
Tensor sizes come from TensorHandle::total_bytes(); the pass runs before Materialization, so sizes are taken from declared dims rather than realized allocations.
Future improvements
Replace the greedy last-consumer heuristic with a cost-model-driven schedule that minimizes true peak footprint (e.g. lookahead or a liveness-interval formulation) instead of a per-step local choice.
- class einsums.graph.RunMetrics#
What the last replay of a graph did, as
Graph::last_runreports it.Measured, beside what the passes planned:
peak_bytesis whatpasses::MemoryPlanning::peak_memorypredicts, and a backing’s bytes are what SlabStreaming’s report estimates.Added in version 2.0.0.
- nodes: list[NodeRun]#
Every node the replay ran, the graph’s own and its bodies’. Each graph’s nodes are in the order they first ran, and a body’s come before those of the graph holding it, since a body’s replay finishes first.
- backings: list[BackingRun]#
One entry per backing in the graph and its bodies, in name order.
- peak_bytes: int#
The most bytes of graph-managed tensors held at once: deferred tensors the graph allocated and freed, plus
arena_bytes. Not the process’s memory: BLAS scratch is outside it, and the caller’s own tensors are inresident_bytes.
- class einsums.graph.ScaleAbsorption#
Scale-elimination pass: removes a Scale by deleting it (dead) or folding its factor into a consumer’s prefactor (live).
A scale is in-place (C *= α), so its live range ends at the tensor’s next writer. It is eliminated in two ways:
Dead-scale removal — the next node writing the tensor overwrites it without reading its prior contents (c_prefactor / beta == 0) and nothing reads it in between, so the scale’s result is discarded wholesale:
Einsum: Scale(α) + Einsum(c_pf=0) → Einsum(c_pf=0)
BatchedGemm: Scale(α) + BatchedGemm(beta=0) → BatchedGemm(beta=0)
Permute: Scale(α) + Permute(beta=0) → Permute(beta=0)
Fold (live scale) — the scaled tensor is overwritten later, so its scaled value is observable only to the nodes in between. Every one of those nodes takes the factor and the Scale is dropped. Two ways a node can take it:
Operand: it reads the tensor as one operand. einsum and axpby are linear in their source, so α folds into ab_prefactor / alpha: Scale(α, A) + Einsum(ab_pf, …, A, B) + overwrite(A) → Einsum(ab_pf·α, …, A, B)
Accumulator: it accumulates into the tensor and reads it only as that destination. scale(α, C) then C = c_pf·C + … is exactly C = (c_pf·α)·C + …, so α folds into c_prefactor / beta: Scale(α, C) + Einsum(c_pf≠0, C, …) → Einsum(c_pf·α, C, …)
The fold is all-or-nothing across the window: if any observer cannot take the factor the whole Scale is kept, because a partial fold would be wrong rather than merely a missed optimization.
The fold is written to BOTH the live EinsumParams (read by the CPU executor) and the descriptor snapshot (read by GPU dispatch / later passes); a descriptor-only edit would desync them — the reason only ops with live shared params are folded into. Because the fold removes a writer that the einsum read, it deliberately flips that read to the tensor’s initial contents; the pass declares the (einsum, tensor) pair via
compensated_readsso the program-order validator waives its structural guard for exactly that read.Example (C++)
cg::Graph graph("scale_absorption"); { cg::CaptureGuard const capture(graph); cg::scale(3.0, &A); // A *= 3 cg::einsum("ij <- ik ; kj", 0.0, &C, 1.0, A, B); // C = 3·(A·B) -- A is the sole reader cg::einsum("ik <- i ; k", 0.0, &A, 1.0, x, y); // A overwritten (its scaled value is dead) } graph.apply(cg::PassManager::create_default()); // ScaleAbsorption runs here // The Scale is gone and the first einsum's ab_prefactor is now 3.Example (Python)
import einsums, einsums.graph as cg g = cg.Graph("scale_absorption") with cg.capture(g): einsums.linalg.scale(3.0, A) # A *= 3 einsums.einsum("ij <- ik ; kj", C, A, B) # C = 3·(A·B) einsums.einsum("ik <- i ; k", A, x, y) # A overwritten sa = cg.ScaleAbsorption() pm = cg.PassManager(); pm.add(sa) g.apply(pm) # or cg.default_pass_manager() # sa.num_absorbed -> 1 (getters are exposed as properties, not methods)
Limitations
Only einsum and axpby can take the factor. gemm, permute and BatchedGemm bake their prefactors into the executor closure, so folding into them is not desync-safe (they lack live shared params); a scale whose window contains one of them is kept.
The tensor must be read as exactly ONE operand by each observer: the tensor used as both einsum operands, or accumulated into AND used as an operand by the same node, would need α² and is left un-folded.
A scaled value that is never overwritten stays observable to the caller after execute, so its Scale is always kept.
A scale whose buffer is also accessed through a VIEW while the scaled value is live is kept. A slice consumer’s prefactor scales only its own span, where the scale covers the whole buffer, so the scale’s effect on the regions no slice touches (padding, unused slots) is observable and nothing can stand in for it. This holds for the dead-scale route too: a later whole-tensor overwrite does not make the scale dead when a view write in between read the scaled bytes.
Only ops with live shared params can take the factor at all, so the grouped ops (GroupedBatchedGemm, GroupedDot, GroupedAxpby) and every kind this pass does not enumerate veto rather than fold.
Reads from inside a control-flow node’s sub-graphs count (via
Graph::effective_io) but cannot be folded into, so a loop body reading the scaled tensor keeps the Scale.
Future improvements
Fold into permute / BatchedGemm / gemm once they carry live prefactor params the way EinsumParams and AxpbyParams do (CG audit §5.1-3).
- class einsums.graph.ScalingAnalysis#
Report how a program scales: every contraction’s cost polynomial, and what limits it.
The user-facing face of the symbolic cost model. It walks the graph, asks
symbolic_cost_forfor each contraction’s cost, adds up the flops, sizes the intermediates, and names the node whose polynomial dominates. Nothing is rewritten and nothing is decided; the point is to answer “what is the rate-limiting term” beside the question “how fast is this”, and to be the first consumer that proves a program’s space annotations are the ones its author meant.Three surfaces carry the same numbers:
explain, the two or three lines that joingraph.explain(),print_report, the full per-node table,the accessors (
node_costs,total_flops,rate_limiting, …) for tests and tooling.
What is analysed
Contraction nodes only. Every other kind is counted in
skip_reasonsand contributes nothing: inventing a cost formula for an op whose cost model has not been written would put numbers in the report that no pass agrees with.Where the letters come from
A node’s cost is derived from the spaces its operands’ handles carry AT THE TIME THE PASS RUNS, not from the
letter_spacesmap frozen into the node at capture. That is what makes the report reflect a declaration that arrived after capture, and everythingSpacePropagationinferred immediately before this pass in the default pipeline. Letters that no annotated slot reaches, and letters whose slots contradict each other, fall back to the node’s captured map and then to an anonymous per-letter variable, so an unannotated program still yields a complete report, just one written in?irather than ino.Example (C++)
cg::Graph graph("scaling"); graph.set_space_registry(registry); graph.annotate_spaces(T2, {occ, occ, virt, virt}); { cg::CaptureGuard const capture(graph); cg::einsum("ijab <- ijcd ; cdab", &R2, T2, Vvvvv); } auto [modified, scaling] = graph.apply<cg::passes::ScalingAnalysis>(); // scaling.total_flops().to_string(®istry) == "2*o^2*v^4" scaling.print_report(std::cout);Example (Python)
scaling = cg.ScalingAnalysis() pm = cg.PassManager() pm.add(scaling) pm.run(g) assert scaling.total_flops_str() == "2*o^2*v^4" print(scaling.report_string())
Python sees the polynomials as their renderings rather than as
SymbolicPolyobjects; see the rendered surface on this class.Limitations
Analysis only.
runalways reports “not modified”.memory_boundis the SUM of the intermediate sizes, which is an upper bound on the high-water mark and not the high-water mark itself. A liveness-aware figure needs the interval analysisMemoryPlanningalready does for bytes, applied to polynomials, and that is a later task. Read it as “no more than this”, never as “this much”.A loop body is analysed once, not once per iteration: a trip count is a runtime quantity and multiplying a polynomial by it would put a number in the report that the symbolic layer cannot defend. Node and tensor entries carry their graph’s name so a body’s contribution stays attributable.
An intermediate is sized from the index letters of the contraction that writes it. An intermediate no contraction writes gets no entry, and is counted in
skip_reasons.The rate-limiting verdict ranks flops only, through the same total order the structural passes use. Two nodes tie only when their flop polynomials are literally identical, so a tie is a statement about the program rather than an artifact of the comparison.
Future improvements
A liveness-aware memory high-water polynomial, once intervals and polynomials meet.
Cost formulas for the non-contraction kinds that have one, starting with Gemm and the element-wise family.
A Python surface for the polynomials themselves, once
SymbolicPolyis worth binding as a type. Today Python reads their renderings.
- report_string() str#
The same report
print_reportwrites, returned as a string.The form a caller that is not holding a stream wants, which is every Python caller and every test that asserts on what the report says. Streams are not bound, and a returned string needs no flushing to be readable.
- Returns:
The report. Never empty; it says so when nothing was analysed.
- total_flops_str() str#
The rendering of
total_flops.- Returns:
The polynomial as text, in the analysed graph’s scale symbols.
- total_traffic_str() str#
The rendering of
total_traffic.- Returns:
The polynomial as text, in the analysed graph’s scale symbols.
- memory_bound_str() str#
The rendering of
memory_bound.- Returns:
The polynomial as text. See the class documentation for what the bound does not say.
- node_labels() list[str]#
The label of every analysed node, in the order they were visited.
- Returns:
The labels, parallel to
node_flops.
- node_flops() list[str]#
The rendered flops polynomial of every analysed node, in the order they were visited.
- Returns:
The renderings, parallel to
node_labels.
- rate_limiting_labels() list[str]#
The labels of the rate-limiting nodes.
- Returns:
The labels. More than one entry only when their flop polynomials are identical.
- intermediate_names() list[str]#
The name of every sized intermediate, in the order they were visited.
- Returns:
The names, parallel to
intermediate_sizes_str.
- intermediate_sizes_str() list[str]#
The rendered element-count polynomial of every sized intermediate.
- Returns:
The renderings, parallel to
intermediate_names.
- class einsums.graph.ScratchPrivatization#
Break false dependencies from reused scratch buffers by renaming each reuse onto its own clone.
Captured code that recycles one scratch tensor through many unrelated write→read episodes – the CCSD idiom
for each term: tmp = contract(...); r2 += tmp– serializes the whole graph: every overwrite oftmpcarries a WAR edge from the previous episode’s readers and a WAW edge from its writer, so operations that share no data still execute strictly one after another and a parallel executor finds no width.The pass splits each such tensor’s accesses into generations (a generation starts at every pure overwrite: a node that writes the whole tensor without reading it) and renames the interior generations onto a bounded pool of clones, round-robin. The LAST generation keeps the original tensor, so every value observable after the graph (or one loop-body replay) completes is unchanged – which is what makes the rewrite safe without knowing who else holds the tensor: outside observers can only look between executions, and between executions the original buffer holds exactly the value it always did.
Clones are declared as graph-owned deferred intermediates (Materialization allocates them, FreeInsertion and MemoryPlanning manage them like any other scratch), and the pool is capped – more clones than the machine has cores adds memory without adding parallelism.
A tensor is left alone whenever renaming can’t be proven safe locally:
any access through a view (a partial write is not a generation boundary),
any read before the first pure overwrite (the value is carried in from outside, e.g. across iterations),
any touch by a control-flow or lifecycle node, or by a node kind the pass cannot rebuild,
fewer than two generations (nothing to split).
Renaming a node means rebuilding its executor: captured executors resolve operands through TensorSlot pointers baked at capture time, so editing
Node::inputsalone would change the schedule but not the computation. Einsum nodes are rebuilt throughGraph::make_einsum_node; Permute and Axpby nodes get executors that resolve their operands by TensorId at call time.In the default pipeline (after LoopInvariantHoisting, before ContractionPlanning): late enough that the structural rewrites (SymmetrizedAccumulation, LCCF, hoisting) have settled, early enough that the planning and memory passes see the renamed graph. Recursion into loop bodies is innermost-first and self-driven.
Example (Python)
import einsums, einsums.graph as cg g = cg.Graph("sp") body = g.add_loop("iter", n, cont) with cg.capture(body): einsums.einsum("ij <- ik ; kj", tmp, A1, B1); einsums.linalg.axpby(1.0, tmp, 1.0, acc) einsums.einsum("ij <- ik ; kj", tmp, A2, B2); einsums.linalg.axpby(1.0, tmp, 1.0, acc) body.set_executor(cg.DataflowExecutor()) # BEFORE apply: the pass rewrites only executor-carrying graphs g.apply(cg.default_pass_manager()) # the two contractions can now overlap
Limitations
Only Einsum, Permute (single-input) and Axpby nodes are rebuilt; a generation touched by any other node kind disqualifies the tensor. Notably a SymmetrizedAccumulation-rewritten permute (two inputs) is skipped deliberately: its descriptor no longer matches its baked executor.
Trusts declared node I/O, like every other pass; an executor touching a tensor it does not declare was already unsound under Reorder.
No profitability model beyond the pool cap: with the sequential executor the rewrite only spends memory.
- __init__() None#
- __init__(max_copies: int) None
- Parameters:
max_copies – Clone-pool cap per tensor; 0 means “number of hardware threads”.
- set_require_executor(require: bool) None#
By default the pass rewrites only graphs that carry an installed executor (Graph::set_executor): under the built-in sequential replay the clones cost cache locality and buy nothing, so a graph that will never run wide is left alone.
Install the executor BEFORE apply(). Setting this false privatizes unconditionally (tests, custom drivers).
- class einsums.graph.SequentialExecutor#
Sequential executor, executes nodes in topological order.
This is the default execution strategy. Nodes run one at a time in dependency order. Zero overhead, no thread safety concerns.
- class einsums.graph.SerializabilityBlocker#
One node that blocks a graph from being saved, and what blocks it.
See also
Graph::serializability_report
- subgraph_path: str#
Where the node lives relative to the graph the report was asked of.
Empty for a node of that graph itself. Otherwise a
/-separated path of the control-flow nodes descended through, each named by its label and, for aConditional, by which branch was taken:loop(scf_iter)/then(converged).A NodeId is graph-local, so
node_idalone does not locate a node inside a body. This is what makes the pair addressable.Added in version 2.0.0.
- class einsums.graph.SlabStreaming#
Read a backed tensor a slab at a time instead of loading it whole.
A tensor annotated with a backing (
Graph::annotate_backing) is loaded whole before its first reader, which needs memory for all of it. This pass rewrites each contraction that reads one into a loop over blocks of the backed tensor’s LAST axis: every iteration reads one slab from the storage into a buffer the size of the block, then runs the same contraction on it. The last axis because the storage keeps elements column-major, so a block of the last axis is one contiguous extent, read in one piece. A backed tensor no node reads whole any more is then never allocated.What a block does to the destination follows the letter the last axis carries. When the destination carries it too, each block writes its own slice and the result is the captured one exactly. When the letter is summed, the blocks add into the destination: the first block applies the destination’s prefactor and the rest add, which is the captured contraction’s own order of operations with its sum cut into parts, so the result moves within the re-association tolerance.
A tensor with a WRITE backing is streamed the other way. The contraction that produces it becomes a loop over blocks of its last axis: every iteration computes one block into a buffer the size of the block and writes that slab to the storage, so the tensor is never held whole. The contraction must overwrite the tensor (a destination prefactor of zero), be its only writer in memory, and read no backed tensor; otherwise the tensor is produced in memory and Materialization stores it whole after its last writer. Its readers are streamed as any backed tensor’s are, but only once nothing writes it in memory, and they run after the writes: every read and write of a storage carries the storage’s key.
It acts only under a memory budget, the same one AxisTiling plans against: a backed tensor is streamed when it is larger than its share of
--einsums:max-memory(--einsums:graph:tiling-budget-share). One that fits is loaded once per replay, which beats one read per reading contraction. It runs after AxisTiling and inside every loop body, so a contraction AxisTiling placed in a block loop is streamed there.Declined, with the reason in the skip tally, and left to the whole load: a backed tensor whose last-axis letter is repeated in any operand or the destination; one read through a view other than a full one; a contraction that reads one backed tensor on both sides; one with permutation operators; any node but a contraction; operands that are not rank-erased tensors. A backed operand held in memory anyway, one that fits or that the graph wrote, is an ordinary operand, and of two backed operands both over their share the larger is streamed and the smaller held.
The slab reads run in order with the contraction: a block’s read finishes before its contraction starts. A graph this pass has rewritten cannot be saved, like one AxisTiling has rewritten; save the graph before the resource passes.
Added in version 2.0.0.
- set_slab_budget(bytes: int) None#
Override the slab budget for this pipeline, in bytes.
Added in version 2.0.0.
- Parameters:
bytes – A backed tensor larger than this is streamed, in slabs no larger than it. Zero turns the pass off; a negative value derives it from
--einsums:max-memoryand--einsums:graph:tiling-budget-share, which is the default.
- stored_order(name: str) list[int]#
The order the last apply left a backed tensor stored in.
Added in version 2.0.0.
- Parameters:
name – The backed tensor’s name.
- Returns:
The declared axis at each stored position, as
TensorBacking::stored_ordergives it; empty for a tensor the apply moved no box of, or whose storage has no order.
- num_streamed: int#
How many contractions the last apply streamed.
Added in version 2.0.0.
(read-only)
- streamed: list[str]#
The backed tensors the last apply streamed, by name, one entry per streamed contraction.
Added in version 2.0.0.
(read-only)
- num_written: int#
How many of the streamed contractions produce their tensor into its storage.
Added in version 2.0.0.
(read-only)
- class einsums.graph.SpaceDim#
One dimension of a declared tensor, given as an index space rather than a number.
Converts implicitly from
SpaceIdso a shape reads as what its axes MEAN ({occ, virt}). An axis that is genuinely a fixed size is spelledfixed({occ, fixed(3)}).There is deliberately NO implicit conversion from an integer. A braced list of plain numbers must keep selecting the dims-based overload unambiguously, and an all-literal shape means the caller opted out of spaces entirely -
fixedis how they say that about one axis while still naming spaces for the others.See also
fixed
Added in version 2.0.0.
- class einsums.graph.SpaceId#
Opaque handle to a space held by a
SpaceRegistry.Stable for the life of the registry that issued it, meaningless anywhere else. A default-constructed id is invalid and every registry query rejects it.
- class einsums.graph.SpacePropagation#
Infer per-slot index spaces on graph intermediates.
Walks the graph in topological order and, for each node that produces a tensor, works out what each output slot ranges over from the annotations its operands carry. When every slot resolves, the output’s
TensorHandle::spacesis filled in and markedTensorHandle::spaces_inferred. That is what keeps annotation effort proportional to a program’s INPUTS rather than to its node count: a method annotates its handful of persistent tensors once, and every intermediate derived from them gets its spaces for free.Current rules
Einsum: the output slot takes the space of the letter that produced it, from the letters bound by the two input operands’ slots.
Scale:
C = α·Ainherits A’s spaces (a scale changes values, never what an axis ranges over).Permute / Transpose: the output slots take the input’s spaces reordered by the node’s own index letters, so
ji <- ijon an(occ, virt)tensor yields(virt, occ).Axpby: the output takes the spaces every annotated input agrees on, slot by slot.
Scope
Only annotates graph-owned intermediates (
is_intermediate == true). A user-owned tensor is never written to, and an unannotated INPUT never has a space pushed back onto it: inheritance across operands is deliberately off, because it is precisely how one wrong annotation spreads silently through the region a validation pass exists to police. Propagation flows from producer to output and nowhere else.An annotation the user DECLARED is never overwritten. One this pass or capture inferred may be refined, and re-inferring the same value is a no-op, so repeated runs converge.
In the default pipeline it sits beside SymmetryPropagation, after Materialization and before GPU placement. The two are independent analyses of the same shape, and neither reads the other’s output.
Example (C++)
cg::Graph graph("space_propagation"); auto &T = graph.create_zero_tensor<double, 2>("T", nocc, naux); auto &U = graph.create_zero_tensor<double, 2>("U", nocc, nocc); { cg::CaptureGuard const capture(graph); cg::einsum("ix <- ia ; ax", &T, A, B); // T is (occ, aux) cg::einsum("ij <- ix ; jx", &U, T, T); // U is (occ, occ), through T } graph.annotate_spaces(A, {occ, virt}); // declarations may arrive after capture graph.annotate_spaces(B, {virt, aux}); auto [modified, pass] = graph.apply<cg::passes::SpacePropagation>(); // pass.num_inferred() == 2: T from A and B, then U from T, in one topological sweep.Example (Python)
cg.annotate(A, ("occ", "virt"), graph=g) cg.annotate(B, ("virt", "aux"), graph=g) prop = cg.SpacePropagation() pm = cg.PassManager() pm.add(prop) pm.run(g) assert prop.num_inferred == 2
Limitations
Analysis-only: the pass never changes the node list, it only annotates
TensorHandleobjects. It always reports “not modified”.Annotates only graph-owned intermediates; user-owned tensors are never mutated.
Soundness guard: a tensor is annotated only when it has exactly one writer in this graph and is not referenced by a child sub-graph, the same rule SymmetryPropagation uses. A second writer could bind the slot to something else, and a nested loop body’s writes are invisible in this graph’s node list.
All-or-nothing per tensor: a rule that cannot resolve EVERY output slot writes nothing, since a half-filled annotation is indistinguishable from a deliberately partial one.
Operands that disagree about a letter are declined and counted in
skip_reasonsrather than reported. A cross-space conflict is a diagnosis for a validation pass to deliver, and this pass has no business failing a pipeline over it.Only the four rules above fire. Every other op kind, including Gemm, BatchedGemm and the grouped ops, leaves its output unannotated.
Future improvements
Cover the remaining structure-preserving kinds: Gemm and Gemv, the grouped and batched forms, element-wise products and quotients, and View, whose slots are its parent’s.
Optional inheritance onto unannotated inputs, off by default, for a partially annotated program whose author accepts the weaker verdict that then follows.
- class einsums.graph.SpaceRegistry#
Spaces, the relations declared between them, and the policy table keyed by their names.
Declared versus derived
A declaration is a fact the caller asserts and the registry stores. A query answers from the closure of those facts, and NOTHING is inferred at declaration time:
Scale order is stored as declared edges and queried through their transitive closure, so
o< v andv< x answero< x.Containment is stored as declared edges and queried through their transitive closure, extended with the reflexive case: a space is contained in itself.
Disjointness is stored symmetrically as declared, and queries additionally derive it through containment on either side: if
ais insidebandbis disjoint fromc, thenais disjoint fromc, and so is everything insidec.
Containment does not imply scale order; declare it if wanted.
Consistency
An inconsistent declaration throws
std::invalid_argument, in either order: no space may lie in two disjoint spaces, scale order may not cycle, and self-relations are rejected.Thread safety
One mutex guards everything; not a hot path. References from
spacelive as long as the registry.- register_space(space: IndexSpace) SpaceId#
Register a space, or recover the id of an identical one already registered.
Never overwrites. Callers meaning different spaces need separate registries (
Graph::set_space_registry).- Parameters:
space – The space to register. Its name must not be empty.
- Returns:
The id of the registered space.
- Raises:
Exception – if the name is empty, or if a space of that name is already registered with different content. The message names every field the two declarations disagree on and both values, through
describe_space_conflict.
- find(name: str) SpaceId | None#
Look a space up by name.
- Parameters:
name – The name to look for.
- Returns:
The id, or an empty optional when no space of that name is registered.
- space(id: SpaceId) IndexSpace#
The space an id names.
- Parameters:
id – The id to resolve. Must be valid and must come from this registry.
- Returns:
The registered space. The reference stays valid for the life of the registry.
- Raises:
Exception – if the id is invalid or out of range.
- declare_less(smaller: SpaceId, larger: SpaceId) None#
Declare that the extent of
smalleris below the extent oflarger.- Parameters:
smaller – The space with the smaller scale.
larger – The space with the larger scale.
- Raises:
Exception – if either id is invalid, if the two are the same space, or if the ordering would close a cycle with what is already declared.
- declare_disjoint(first: SpaceId, second: SpaceId) None#
Declare that two spaces share no element.
- Parameters:
first – One space.
second – The other space. The relation is symmetric.
- Raises:
Exception – if either id is invalid, if the two are the same space, or if some space is already known to sit inside both of them (which includes one of them sitting inside the other).
- declare_contained(inner: SpaceId, outer: SpaceId) None#
Declare that every element of
inneris an element ofouter.- Parameters:
inner – The contained space.
outer – The containing space.
- Raises:
Exception – if either id is invalid, if the two are the same space (self-containment is trivially true and asserting it signals a mistake), if the reverse containment is already declared, or if the containment would place some space inside two spaces declared disjoint.
- is_less(smaller: SpaceId, larger: SpaceId) Tristate#
Whether
smallerhas a smaller scale thanlarger.- Parameters:
smaller – The candidate smaller space.
larger – The candidate larger space.
- Returns:
Yes when the closure of the declared orderings puts
smallerbelowlarger, No when it putslargerbelowsmalleror the two are the same space, Unknown when no declared ordering relates them.- Raises:
Exception – if either id is invalid.
- is_disjoint(first: SpaceId, second: SpaceId) Tristate#
Whether two spaces share no element.
- Parameters:
first – One space.
second – The other space.
- Returns:
Yes when disjointness was declared for the pair or follows from containment on either side, No when the two are the same space or one is known to contain the other, Unknown otherwise.
- Raises:
Exception – if either id is invalid.
- is_contained(inner: SpaceId, outer: SpaceId) Tristate#
Whether every element of
inneris an element ofouter.- Parameters:
inner – The candidate contained space.
outer – The candidate containing space.
- Returns:
Yes when the two are the same space or the closure of the declared containments relates them, No when
outeris instead contained ininneror the two are known disjoint, Unknown otherwise.- Raises:
Exception – if either id is invalid.
- class einsums.graph.SpaceTiling#
One axis of a declared TILED tensor: what it means, and how it is cut up.
A tiled axis is described by a PARTITION, not an extent: an index space fixes the total (
occis 4) but{2,2},{1,3}and{4}all tile it. So the two halves are supplied separately, and either may come from the space:{occ, virt} // both axes take their space's canonical tiling {{occ, {2, 2}}, {virt, {4, 4}}} // this tensor tiles differently from the default {occ, tiles({4, 4})} // second axis is a partition with no chemical meaningConverts implicitly from
SpaceIdso the first form needs no ceremony. There is no conversion from a bare tile list, so a plain{{2,2},{4,4}}keeps selecting the tile-sizes overload unambiguously;tilesis how a space-less axis joins a shape that names spaces elsewhere.See also
tiles
See also
Graph::pin_space_tiling
Added in version 2.0.0.
- class einsums.graph.StreamContractionFusion#
Fuse contractions that stream the same large tensor into one pass over it (the SCF “J and K from one TEI read” idiom).
Detects groups of einsum nodes that each contract the SAME large tensor \(S\) against a small operand, where every output index and every small-operand index is drawn from \(S\)’s index pattern (the “GEMV-shaped” class: each element of \(S\) is read exactly once and contributes \(\alpha_k\,S[\mathrm{idx}]\,W_k[\pi_k(\mathrm{idx})]\) to \(C_k[\rho_k(\mathrm{idx})]\)). Such contractions are memory-bandwidth bound - their cost is one stream of \(S\) - so \(N\) of them cost \(N\) streams executed separately, but only ONE stream when fused: the replacement node walks \(S\) once in storage order and feeds every member’s accumulator from the same element.
Example (Fock build)
Before (two 800 MB streams of the TEI at n = 100, plus the scrambled K pattern running below stream speed):
// J[mu,nu] += 2 * TEI[mu,nu,lam,sig] * D[lam,sig] // K[mu,nu] -= 1 * TEI[mu,lam,nu,sig] * D[lam,sig]
After: one storage-order stream of TEI updating both J and K, with thread-private accumulators for the (small) outputs.
Members may write different outputs (J and K) or accumulate into a shared one; for a shared output every member after the first must purely accumulate (c prefactor 1), mirroring
LinearCombinationContractionFolding’s tail rule. Conjugated members and repeated indices are left unfused. Complex prefactors fuse on complex tensors (the kernel carries element-typed alphas); on real tensors a prefactor with a nonzero imaginary part declines the member rather than silently dropping it. The streamed tensor must dominate the member operands and outputs in size (ratio gate below).Output handling: privatization, with owner-computes chunking above the cap
Outputs are normally accumulated in thread-private buffers and reduced at the end, which requires them to stay cache-resident: with a
CostModelcarrying cache sizes the cap is derived as last-level-cache / threads bytes per output (so the aggregate private buffers fit in cache); without one a fixed fallback applies. When a member’s output exceeds the cap, the group switches to owner-computes chunking instead of declining: partitioning a physical \(S\) axis whose label lands in the output pins one output coordinate, so threads owning disjoint blocks of that axis write disjoint output slices directly - no private copy, no reduction, no size cap. An axis covers a member only when every member writing the same output puts its label in the same place there: members accumulating into one output through transposed patterns would hand each thread a row stripe and a column stripe, and the stripes of different threads cross. The pass records every axis that covers all over-cap members; the kernel partitions the highest-stride one (a low-stride partition turns each thread’s read into a strided comb, measured ~5x slower than contiguous slabs). Under-cap members not covered by the chosen axis keep their private buffers inside the same stream. An over-cap member no axis can cover drops out of the group and stays an ordinary einsum. Groups with all outputs under the cap keep the flat privatized walk unconditionally - its contiguous per-thread slabs are the measured-fastest layout.Aliasing: every operand is compared as a BUFFER
Fusion interleaves the members and moves every member’s write to the first member’s position, so it is only equivalent to the original order when no member’s write is observable by another member or by any node it moves across. Both questions are decided on
Graph::resolve_aliasroots rather than TensorIds, because a view and its parent are different ids over one buffer - and in a real capture views are the common case (a DLPNO-CCSD iteration registers ~5800 of them against ~1200 whole tensors). A group declines when an output shares a buffer with the streamed tensor, with a weight, or with another output, and when any node between the members shares a buffer with one of them. The graph merges partially overlapping byte spans into one buffer, so two interleaved strided slices of one parent count as shared even though their elements are disjoint; proving such slices apart would need the per-view interval boxes the hazard scan builds (Graph::for_each_hazard_edge), which this pass does not read yet. Until it does, a view-heavy graph is where the pass declines most.Relationship to LinearCombinationContractionFolding
LCCF serves the same 2J-K algebra by materializing a linear combination \(L\) of the streamed tensor and contracting once - measured 2.7x over unfused for the Fock idiom, but it still makes ~4 passes over \(S\)-sized data. This pass replaces those with a single pass. When both passes are registered, run this one FIRST: it consumes the pattern LCCF would otherwise fold.
Opt-in
Registered in
PassManager::create_default(after Materialization / SymmetryPropagation, before GPU placement): the size and ratio gates make it a no-op on graphs without a qualifying stream, and it declines distributed operands.cg::PassManager pm; pm.add(std::make_shared<StreamContractionFusion>()); graph.apply(pm);
Example (Python)
import einsums, einsums.graph as cg g = cg.Graph("stream_fusion") with cg.capture(g): # Two contractions streaming the same large TEI against the small density D. einsums.einsum("mn <- mnls ; ls", J, TEI, D, c_pf=0.0, ab_pf=2.0) # J += 2 * TEI * D einsums.einsum("mn <- mlns ; ls", K, TEI, D, c_pf=0.0, ab_pf=-1.0) # K -= 1 * (scrambled TEI) * D g.apply(cg.default_pass_manager()) # StreamContractionFusion runs in the default pipeline # You may also add cg.StreamContractionFusion() to a manual cg.PassManager, but # its num_groups / num_eliminated counters are not exposed as Python properties.
Limitations
Members must be einsum nodes with two inputs and one output, no repeated index in any of C/A/B (diagonal patterns decline), and non-conjugated (conj_a/conj_b decline).
One operand is the streamed tensor \(S\), the other the small \(W\); every C index and every W index must be drawn from \(S\)’s index pattern (the GEMV-shaped class - each element of \(S\) read exactly once).
\(S\), \(W\) and C must all be runtime tensors (owning or view) of one dtype, each with a live
TensorHandle::impl_fn; a mixed-dtype member declines (the kernel casts all three to \(S\)’s element type) and so does a tile-wise sparse operand, which has no single geometry to read.A group declines when its operands share a buffer, or when a node between its members touches one (see the aliasing note above).
On a real dtype, ab_prefactor and c_prefactor must be real-valued; complex prefactors ride through only on complex dtypes.
Distributed operands decline (they belong to the InputSlicing / SUMMAExpansion communication passes).
Size gates: \(S\) needs >= kMinStreamElems (4096) elements and must be >= kMinSizeRatio (8x) larger than each member’s \(W\) and output.
A group needs >= 2 members over the same \(S\), and for a shared output only the first member touching it may have c_prefactor != 1 (contributions interleave in the one stream). An interference guard also rejects the group if any node between the first and last member writes the buffer of an operand or reads the buffer of an output.
Privatized members are held to max_output_elems (cache-derived with a cost_model, a fixed fallback without); an over-cap member is only kept if an owner-computes partition axis covers it, otherwise it drops out and stays an ordinary einsum.
Future improvements
Admit conjugated members and repeated-index (diagonal) patterns, currently declined outright.
Support statically-typed Tensor<T,Rank> captures, not only runtime tensors.
Read the hazard scan’s per-view interval boxes so element-disjoint slices of one parent stop counting as one buffer, which is what currently declines every candidate group in a view-heavy graph.
Coordinate with the communication passes so distributed streams can fuse instead of declining.
- class einsums.graph.SymmetrizedAccumulation#
Fold the CCSD permutational-symmetrization idiom \(r2 \mathrel{+}= s\,(t + P(t))\).
Chemistry residuals accumulate a tensor and its index-swapped transpose into the same output. In the graph this appears as four nodes per site (the
symacchelper inccsd_rhf_graph_numpy_style.py):einsum(spec, A, B) -> tmp // tmp = pf*(A(x)B) (kept) axpby(s, tmp, 1.0, r2) // r2 += s*tmp permute("jiba <- ijab", tmp) -> tmpP // tmpP = P(tmp) (an involution) axpby(s, tmpP, 1.0, r2) // r2 += s*tmp^{jiba}The pass detects each such site (structural match + involutive permutation + accumulate gate + interference guard) and rewrites it (Level 1, permute reuse). The permute node is made to accumulate DIRECTLY into the output, \(r2 = r2 + s_2\,\alpha\,P(t)\), rebuilt as an ordinary permute node with beta = 1 that keeps the permute’s own alpha and permutation operators, and the second axpby and the
tmpPbuffer are deleted. The first axpby (\(r2 \mathrel{+}= s_1 t\)) is untouched. This drops the O(o^2 v^2)tmpPstorage and one full sweep per site with no new kernel or OpKind. Seedocs/symmetrized_accumulation_design.md.Example (C++)
cg::Graph graph("symacc"); { cg::CaptureGuard const capture(graph); cg::einsum("ijab <- ia ; jb", 0.0, &tmp, 1.0, A, B); // tmp = A (x) B cg::axpby(0.5, tmp, 1.0, &r2); // r2 += 0.5*tmp cg::permute("jiba <- ijab", 0.0, &tmpP, 1.0, tmp); // tmpP = P(tmp) cg::axpby(0.5, tmpP, 1.0, &r2); // r2 += 0.5*P(tmp) } graph.apply(cg::PassManager::create_default()); // tmpP and the second axpby are gone; the permute now does r2 += 0.5*P(tmp).Example (Python)
import einsums, einsums.graph as cg g = cg.Graph("symacc") with cg.capture(g): # runtime tensors (the workload path) einsums.einsum("i,j,a,b <- i,a ; j,b", tmp, A, B) # tmp = A (x) B einsums.linalg.axpby(0.5, tmp, 1.0, r2) # r2 += 0.5*tmp einsums.permute("j,i,b,a <- i,j,a,b", tmpP, tmp) # tmpP = P(tmp) einsums.linalg.axpby(0.5, tmpP, 1.0, r2) # r2 += 0.5*P(tmp) sa = cg.SymmetrizedAccumulation() pm = cg.PassManager(); pm.add(sa) g.apply(pm) # or cg.default_pass_manager() # sa.num_rewritten -> 1 (getters are properties, not methods)
In the default pipeline (after DeadNodeElimination, before ElementWiseFusion — which would otherwise compose the two axpby and hide the pattern). Recurses into loop bodies: the CCSD residual is captured as a loop body.
Limitations
The source and the output must hold one element type, and a real output is never folded under a complex factor.
The source may be read through a view, but the output and
tmpPmay not be views: the folded node would write the output’s parent storage, andtmpPmust be storage no other id names. The source may not share the output’s storage either, since the folded node reads one while writing the other.Level 1 keeps the transpose (the accumulating permute), so REPLAY TIME is ~compute-neutral (a few %, transpose-bound). The win is eliminating the O(o^2 v^2)
tmpPbuffer (peak memory), not compute.Detection requires the exact structure: an involutive overwrite permute whose output is consumed, within the generation this permute starts (up to the buffer’s next overwrite), by exactly one accumulating axpby, plus a sibling accumulating axpby reading the un-permuted source into the same output from the source’s own generation. Scratch REUSED across sites (the CCSD body recycles one tmp/tmpP for every term) matches per generation; an interference guard rejects sites where another node observes the half-symmetrized output.
Future improvements
Level 2: a fused single-sweep
SymmetrizedAxpbykernel (\(r2 \mathrel{+}= s_1 t + s_2 P(t)\) in one pass), profiling-gated — drops the second sweep as well, not just the buffer.Generalize beyond involutive permutations and allow \(s_1 \neq s_2\).
Accept a view as the output: the folded node reaches it through its impl, so what is left is proving the interference guard sees every other view of it.
- num_candidates: int#
Structural matches: permute (involutive, overwrite) whose output feeds, within the generation this permute starts, exactly one accumulating axpby into an output that a sibling accumulating axpby also feeds from the un-permuted source’s generation.
(read-only)
- class einsums.graph.SymmetryPropagation#
Phase 3 of the symmetry plan: infer symmetry on graph intermediates.
Walks the graph in topological order. For each node that produces a tensor, checks whether the output can be proven symmetric / antisymmetric / Hermitian from the inputs’ declared descriptors, and if so tags the output
TensorHandleand pushes the descriptor back to the backing tensor (so subsequentgraph.execute()benefits from the rank-2 BLAS dispatch in LinearAlgebra/SymmetryDispatch.hpp).Current rules
Scale:
C = α·Ainherits A’s descriptor (scaling preserves symmetry).Axpy / Axpby / sum of same-descriptor inputs:
C = α·A + β·Bwhere A and B share a descriptor inherits that descriptor.Permute / Transpose of a rank-2 symmetric tensor with the natural swap-permutation remains symmetric.
Einsum ``ki,kj->ij`` (pattern ``AᵀA``): the product of A with its own transpose is always symmetric (for real) / Hermitian (for complex) regardless of A.
Rules are deliberately conservative, only cases that hold unconditionally get tagged. Everything else is left untagged, which is the safe default.
Scope
Only tags graph-owned intermediates (
is_intermediate == true). User-owned tensors are never mutated by this pass.In the default pipeline (after Materialization, so the backing tensors exist, and before GPU placement, so downstream passes and executions see the inferred symmetry).
Example (C++)
cg::Graph graph("symmetry_propagation"); { cg::CaptureGuard const capture(graph); // T = AᵀA is provably symmetric; when T is a graph-owned intermediate // (e.g. produced by ContractionPlanning or declare_tensor) the pass tags it. cg::einsum("ij <- ki ; kj", 0.0, &T, 1.0, A, A); // T symmetric cg::einsum("il <- ij ; jl", 0.0, &C, 1.0, T, B); // consumer sees the tag } graph.apply(cg::PassManager::create_default()); // SymmetryPropagation runs here // T's handle is tagged symmetric, enabling the rank-2 BLAS dispatch at execute().Example (Python)
import einsums, einsums.graph as cg g = cg.Graph("symmetry_propagation") with cg.capture(g): einsums.einsum("ij <- ki ; kj", T, A, A) # T = AᵀA (symmetric intermediate) einsums.einsum("il <- ij ; jl", C, T, B) sp = cg.SymmetryPropagation() pm = cg.PassManager(); pm.add(sp) g.apply(pm) # or cg.default_pass_manager() # sp.num_inferred -> number of tensors tagged (getter is a property, not a method)
Limitations
Analysis-only: the pass never changes the node list. It only tags the
TensorHandleobjects and pushes descriptors to the backing tensors.Tags only graph-owned intermediates (
is_intermediate); user-owned tensors are never mutated.Soundness guard: a tensor is tagged only when it has exactly one writer in this graph and is not referenced by a child sub-graph (a nested loop/conditional body could rewrite it invisibly), so nothing can invalidate the tag later.
Only four rules fire, all unconditional: Scale (inherit), Axpy/Axpby whose two inputs carry identical descriptors, rank-2 Permute/Transpose with the swap permutation and a zero destination prefactor on a symmetric/Hermitian input, and the self-contraction einsum (same tensor in both operand slots, rank-2 x rank-2 -> rank-2 with exactly one link index).
The permute rule is rank-2 only and propagates only symmetric/Hermitian pair descriptors (higher-rank descriptors can encode cross-axis invariants that do not carry through every permute).
Everything not provably structured is left untagged (the safe default).
Future improvements
Add rules for more op kinds: general einsum symmetry inference, antisymmetric outputs, propagation through gemm / BatchedGemm nodes.
Relax the rank-2-only permute rule to higher-rank symmetry descriptors once the cross-axis invariants are tracked.
- class einsums.graph.TensorBacking#
The storage behind a tensor the graph reads, or writes, but never holds whole.
kindandlocationare what a saved graph records, withwrite.dimsanddtypedescribe what the storage holds and are checked against the tensor when the backing is annotated, so a mismatch is reported where it is made rather than at the first replay.read_slabandwrite_slabare rebuilt at load by the registeredBackingKindand never written to a file.A READ backing names storage that already holds the tensor: an input the graph only reads. A WRITE backing names storage the graph fills: the tensor is an output the graph produces, and may read back after producing it. A write backing is completed by the tensor it is annotated on, through
prepare, since the storage may not exist yet to describe it. An UPDATE backing is a write backing whose storage also holds the value each replay starts from: the graph reads the tensor, writes its next value, and the storage is switched to that value at the end of the replay (update,publish), together with every other update backing of the graph that shares itspublish_scope.Built by the module that knows the storage, as
tensor_io::etn_backingbuilds one for a.etnentry, and handed toGraph::annotate_backing.See also
Graph::annotate_backing
See also
register_backing_kind
- describe() str#
The kind and location in one phrase, for diagnostics.
- Returns:
Text such as
tensor_io.etn (entry=B_vv, path=ints.etn).
- dtype: str | None#
The stored tensor’s element type by name, as a
dtype=argument spells it.Added in version 2.0.0.
(read-only)
- location: list[tuple[str, str]]#
Key/value pairs that name the storage within its kind, sorted by key, as in
{{"entry", "B_vv"}, {"path", "ints.etn"}}.
- write: bool#
Whether the graph writes the storage (an output it produces) rather than only reading it.
- update: bool#
Whether the graph also reads the value the storage holds when a replay starts: an UPDATE backing, set with
write.read_slabreads that value,write_slabwrites the next one beside it, andpublishmakes the next one current once the replay has made every access. A crash before the publish leaves the storage holding the previous value.
- publish_scope: str#
Which update backings publish together: those of one graph with the same non-empty scope are published by one call, so a crash leaves all of them at the values the replay started from or all at the values it wrote. A kind sets it to what one atomic step can cover, as
tensor_io.etnsets the file’s path. Empty: published alone.
- class einsums.graph.ThcFactorization#
Offer a four-index tensor as a fitted chain over two grid indices.
See also
ThcFactorization.hpp for the mathematics and for what chemistry calls it
Added in version 2.0.0.
- __init__(tag: str, three_index: Any, collocation: Any, bound: float = 0., drop_threshold: float = einsums::compute_graph::ThcFactorization::default_drop_threshold, name: str = "Thc") None#
- __init__(tag: str, three_index: Any, collocations: list[Any], bound: float = 0., drop_threshold: float = einsums::compute_graph::ThcFactorization::default_drop_threshold, name: str = "Thc") None
The same, taking runtime-rank tensors. This is the overload Python gets.
Note
The drop-threshold default is spelled with its class qualifier because the binding generator copies a default argument through verbatim, and an unqualified class-scope constant does not resolve where the generated code spells it.
- static for_amplitude(tag: str, amplitude: Any, collocations: list[Any], bound: float = 0., drop_threshold: float = einsums::compute_graph::ThcFactorization::default_drop_threshold, name: str = "ThcAmplitude") ThcFactorization#
The same, taking runtime-rank tensors. This is the overload Python gets.
- Parameters:
tag – The provenance tag this claims.
amplitude – The very tensor the caller tags.
collocations – One matrix per axis, or one for every axis.
bound – The relative error asserted, or zero to take the option.
drop_threshold – See
default_drop_threshold.name – The provider’s name.
- Returns:
The provider.
- static for_three_index(tag: str, three_index: Any, collocations: list[Any], bound: float = 0., drop_threshold: float = einsums::compute_graph::ThcFactorization::default_drop_threshold, name: str = "ThcThreeIndex") ThcFactorization#
The same, taking runtime-rank tensors. This is the overload Python gets.
- Parameters:
tag – The provenance tag this claims.
three_index – The very tensor the caller tags.
collocations – One matrix per basis axis, or one for both.
bound – The relative error asserted, or zero to take the option.
drop_threshold – See
default_drop_threshold.name – The provider’s name.
- Returns:
The provider.
- report_residual_into(residual: Any, reference: Any) None#
The same, taking runtime-rank tensors. This is the overload Python gets.
- Parameters:
residual – A rank-1 tensor for the squared residual.
reference – A rank-1 tensor for the squared norm of what was fitted.
- static register_grid_space(graph: Graph) SpaceId#
Register the grid space in
graph'sown registry, if it is not there already.A space is a statement about a graph rather than about a provider, and
proposeis handed a const graph precisely so a provider cannot make one. So a caller registers it, and this is the one call that does: idempotent for a repeated identical declaration, asSpaceRegistry::register_spaceis.- Parameters:
graph – The graph whose registry gains the space.
- Returns:
The space’s id in that registry.
- static residual_param_name(provider: str, tensor: str) str#
The parameter the squared residual of the fit is reported under.
Divided by
reference_param_nameand square-rooted, this is the RELATIVE least-squares residual of the grid fit against the three-index tensor it was fitted from. Per bind and not saved, because it is a property of the grid and the integrals currently bound rather than of the structure.- Parameters:
provider – The provider’s
name.tensor – The tagged tensor’s name.
- Returns:
The key to read out of the graph’s parameter table after an execute.
- static reference_param_name(provider: str, tensor: str) str#
The parameter the squared norm of the three-index tensor is reported under.
- Parameters:
provider – The provider’s
name.tensor – The tagged tensor’s name.
- Returns:
The key. See
residual_param_namefor what the two are for.
- class einsums.graph.WaggleBridge#
An observer that labels the profiler’s zones with what the graph was doing in them.
Every executor opens a zone per node while the profiler records. This adds to it the graph and the node it belongs to, and each read, write and publish of a backing the node made, with its bytes (
read t2,write t2_next), so the live viewer and the saved profile name the graph node behind a zone and the storage traffic inside it. Without the profiler recording, it does nothing.g.set_observer(cg.WaggleBridge())
Added in version 2.0.0.
- class einsums.graph.Workspace#
Owns tensors that persist across multiple Graphs and Pipelines.
Workspace is the outermost scoping layer for tensor lifetime:
Workspace: cross-computation (ERI, MO coefficients, basis data)
Pipeline: cross-stage (Fock matrix, density, amplitudes)
Graph: single-computation intermediates (temporaries)
Tensors declared via Workspace use deferred allocation: they have valid metadata (name, dims, dtype) but no backing data until the MaterializationPass runs. This allows the DistributionPlanningPass to decide how to partition large tensors across MPI ranks before any memory is allocated.
Example
namespace cg = einsums::compute_graph; cg::Workspace ws("h2o"); // Declare tensors, no data allocated yet auto &eri = ws.declare_tensor<double, 4>("ERI", nao, nao, nao, nao); auto &C = ws.declare_zero_tensor<double, 2>("C", nao, nmo); // Use in a pipeline cg::Pipeline scf("scf"); scf.set_workspace(ws); { auto &stage = scf.add_stage("compute"); cg::CaptureGuard guard(stage); cg::einsum("ijkl;kl->ij", 0.0, &F, 1.0, eri, D); } scf.apply(pm); // Passes decide distribution, then materialize scf.execute(); // Computation runs on materialized tensors // eri and C survive, reuse in MP2, CCSD, etc.- declare_runtime_tensor(tensor_name: str, dims: list[int]) GeneralRuntimeTensor#
Runtime-rank analog of declare_tensor().
Same deferred-allocation lifecycle as the typed version (no data until materialize_fn fires) but the rank is carried at runtime. Suitable for Python-bound workflows or any workflow that wants a single dispatch surface across ranks.
- declare_zero_runtime_tensor(tensor_name: str, dims: list[int]) GeneralRuntimeTensor#
Runtime-rank analog of declare_zero_tensor().
Functions#
- einsums.graph.batched_gemm(alpha: float, a_list: list[Any], b_list: list[Any], beta: float, c_list: list[Any], trans_a: bool = False, trans_b: bool = False) None#
Emit one blas::gemm_batch over a batch of independent GEMMs:
C_i = alpha * op(A_i) op(B_i) + beta * C_ifor every i.The GEMMBatching pass already fuses independent 2D einsums into a single BatchedGemm node, so the fused form was reachable without this. What it was not reachable cheaply: the caller had to emit one node per GEMM and let the pass collapse them, and capture costs on the order of tens of microseconds a node. A DLPNO-MP2 residual emitted 8112 nodes for the passes to fuse into 33, spending more time building the graph than replaying it. This lets a caller who already knows the batch say so directly.
Every member must share m, n, k, the transpose flags, the element type and the leading dimensions, which is what gemm_batch takes as scalars. The prefactors are shared too, so a per-member prefactor has to be folded into the operands beforehand. Mismatches throw here rather than at execute time.
Outside capture this executes immediately, so the same call works eagerly.
- Parameters:
alpha – Prefactor on op(A_i) op(B_i), shared by the batch.
a_list – Left operands. Must all be rank 2 with identical dims.
b_list – Right operands, same length as
a_list.beta – Prefactor on C_i. Non-zero means every C_i is read as well as written, which the node records as a dependency.
c_list – Destinations, same length as
a_list. Must be distinct tensors: gemm_batch gives no ordering between members, so two members sharing a destination race.trans_a – Transpose each A_i.
trans_b – Transpose each B_i.
- einsums.graph.batched_gemm_blocked(alpha: float, a_list: list[Any], b_list: list[Any], beta: float, c_base: Any, c_offsets: list[int], c_rows: int, c_cols: int, trans_a: bool = False, trans_b: bool = False) None#
batched_gemmwhere the destinations are uniform-shaped blocks of a single tensor, described by their offsets rather than enumerated as views.The list form needs one tensor object per member, and building those is not free: a caller whose destinations are column ranges of one store has to materialize a view apiece, which in a local-correlation method is tens of thousands of them. On the DLPNO port’s overlap build that is 32948 view constructions on the Python side and 32948 more slot registrations here, together about half the phase, and none of it is arithmetic.
c_offsetsgives each block’s first element as an offset intoc_base, in elements. Every block isc_rowsbyc_colsand inherits the base’s leading dimension, which is what makes them expressible this way: a column range of a column-major tensor has the parent’slda.A and B stay lists, because the callers that want this have destinations that repeat one tensor and sources that do not. Passing a list of existing tensors is cheap; it is constructing the views that is not.
One further difference from the list form, and it is a correctness one: the node declares a single output,
c_baseitself, so a later read of the whole base is ordered against this write. The list form declares the views, and the graph does not know a view write touches its parent, so that ordering has to be forced with a graph boundary.
- einsums.graph.custom(label: str, executor: Callable[[Any], None], pure: bool = False) None#
- einsums.graph.custom(label: str, executor: Callable[[Any], None], target: Any, pure: bool = False) None
No-dependency custom node, Python-friendly overload.
Records a graph node that runs
executorwith no declared input/output tensor dependencies. Outside a capture context the executor runs immediately. Use the tensor-tagged overload below for read-modify-write patterns where the optimizer should see the dependency.A node with no tensors acts only through its effects, so it is recorded with
opaque_effectsunlesspureis true (seePureTag).cg::custom("debug_print", []() { fmt::print("hello\n"); });- Parameters:
label – Human-readable name for profiling and debugging.
executor – Callable that performs the operation.
pure – True to declare the operation pure.
- einsums.graph.diis_add_pair(accelerator: DiisAccelerator, amplitude: Any, step: Any) None#
Register one
(amplitude, step)pair with a DIIS accelerator.amplitudeis the tensor the iteration updates andstepis the update the body computed, which DIIS also uses as the error vector. Both are bound by storage, so they must outlive the accelerator, and every pair has to be added before the first step - the snapshots are shaped for the pair list.This is bookkeeping, not an operation: it records nothing into an active capture and works the same inside and outside one.
- einsums.graph.diis_step(accelerator: DiisAccelerator) None#
Take one DIIS step over an accelerator’s registered pairs.
Outside capture this extrapolates immediately, which is how a host-side convergence loop uses it. Inside capture it records one node whose executor holds the accelerator, so a replay of the graph steps the same history; the node reads every amplitude and step tensor and writes every amplitude, which is what orders it against the body around it.
- einsums.graph.duplicate_materializations(graph: Graph) list[str]#
Tensors with more than one Materialize node, anywhere in
graph'stree.A tensor’s storage is allocated once. Two lifecycles for one buffer survive only because
materialize_fnhappens to be idempotent, which is a property of today’s hook rather than a contract, and the extra node carries a dependency edge that serializes work against itself for nothing. Two passes each emitting one is how it happens, and no numeric oracle can see it: both allocations produce the same buffer and the answer does not move.Keyed by NAME rather than by id, because a sub-graph carries its own id for the parent’s buffer and a name is the one handle both spellings share, which is what
already_materialized_ininside the pass already relies on.- Parameters:
graph – The graph to audit; loop bodies, conditional branches and setup bodies are included.
- Returns:
The names, sorted, of every tensor named by more than one Materialize node.
- einsums.graph.eager_einsum_intermediate_limit(element_size: int) int#
The most elements an eager einsum over several operands lets a partial product hold.
A captured einsum is not limited: its partial products are graph intermediates, and the graph’s
AxisTilingpass builds one a block at a time when it is too large to hold. An eager einsum has no such pass, so its partial products are held to what--einsums:max-memoryallows.Added in version 2.0.0.
- Parameters:
element_size – The bytes of one element.
- Returns:
The limit, or zero for none.
- einsums.graph.fixed(extent: int) SpaceDim#
An axis whose size is a number and whose meaning is nothing.
A DIIS history depth or a fixed block count is a real thing to want in a shape that otherwise names spaces, and it must NOT pick up a dim symbol: a literal axis is one a bind may not move, which is exactly what “fixed” says.
Added in version 2.0.0.
- Parameters:
extent – The size.
- Returns:
The dimension.
- einsums.graph.global_factorization_registry() FactorizationRegistry#
The process-wide provider registry.
Added in version 2.0.0.
- Returns:
The registry. Never null.
- einsums.graph.global_space_registry() SpaceRegistry#
The process-wide space registry.
Register spaces and declare their relations during startup or setup; queries then run from anywhere. The registry’s own mutex makes the concurrent case safe rather than fast.
- Returns:
The single registry shared by every graph in this process.
- einsums.graph.grouped_batched_gemm(alpha: float, a_list: list[Any], b_list: list[Any], beta: float, c_list: list[Any], trans_a: bool = False, trans_b: bool = False) None#
Emit one blas::gemm_batch_grouped over independent GEMMs whose shapes need NOT agree:
C_i = alpha * op(A_i) op(B_i) + beta * C_i.The same signature as
batched_gemm, minus its central restriction. Members are sorted into shape groups here, at capture, and the whole set then runs under ONE OpenMP region instead of one per shape.That is the entire point, and it is not a small one. Entering a region costs tens of microseconds on a wide team, which is comparable to a GEMM of the size local-correlation methods produce. Measured on a DLPNO-MP2 iteration whose batched GEMMs want 16 ms of arithmetic, issuing them as 754 uniform calls took 45 ms and issuing them as one grouped call took 16.7. The same batch also stopped caring how finely it was split: the effective rate held flat at ~230 GFLOPS across 120, 448 and 754 shape classes, where the looped form fell 146 to 80.
Grouping is by (m, n, k, lda, ldb, ldc); the prefactors and transpose flags are shared by the whole call, as they are for
batched_gemm. Groups are numbered in order of first appearance and members keep their relative order inside a group, but members of DIFFERENT shapes are reordered against each other. That is within contract for the same reason the uniform form gives no ordering between members: they must be independent.Outside capture this executes immediately, so the same call works eagerly.
- Parameters:
alpha – Prefactor on op(A_i) op(B_i), shared by the whole call.
a_list – Left operands, all rank 2. Shapes may differ between members.
b_list – Right operands, same length as
a_list.beta – Prefactor on C_i. Non-zero means every C_i is read as well as written, which the node records as a dependency.
c_list – Destinations, same length as
a_list. Must be distinct tensors: the call gives no ordering between members, so two members sharing a destination race.trans_a – Transpose each A_i.
trans_b – Transpose each B_i.
- einsums.graph.grouped_batched_gemm_blocked(alpha: float, a_list: list[Any], b_list: list[Any], beta: float, c_bases: list[Any], c_offsets: list[int], trans_a: bool = False, trans_b: bool = False) None#
grouped_batched_gemmwhere the destinations are blocks of existing tensors, described by a base and an offset rather than enumerated as views.The blocked form of
batched_gemmexists because materializing one view per destination is tens of thousands of pybind round trips in a local correlation method. The grouped form exists because one OpenMP region per shape class costs more than the arithmetic. A caller whose destinations are blocks AND whose shapes differ between classes needs both, and the DLPNO overlap build is exactly that caller: one destination tensor per shape class, every coupling a column range of its class’s tensor.So
c_basesis parallel to the members, not to the groups. Repeating a base pointer across a class’s members is a pointer copy; it is constructing the views that is expensive, and none are constructed. Each block’s shape is derived from its own A and B rather than passed, and its leading dimension from its base, which is what makes a column range expressible this way.The node declares each DISTINCT base as an output, so a later read of a whole base is ordered against this write. The list form declares the views, and the graph does not know a view write touches its parent.
- Parameters:
alpha – Prefactor on op(A_i) op(B_i), shared by the whole call.
a_list – Left operands, all rank 2. Shapes may differ between members.
b_list – Right operands, same length as
a_list.beta – Prefactor on C_i. Non-zero means every block is read as well as written, which the node records as a dependency.
c_bases – Per member, the tensor its block lives in.
c_offsets – Per member, the block’s first element as an offset into its base, in elements.
trans_a – Transpose each A_i.
trans_b – Transpose each B_i.
- einsums.graph.last_dispatch_route_name() str#
The kernel route the most recent contraction on this thread took, as a string.
A copy of
last_dispatch_routefor the Python bindings, which cannot hold the thread-local slot itself. It serves the same purpose: a test asserts that a spec reached its fast path, since a fallback to the generic loop still computes the right values and only the route shows it. Read it on the thread that ran the contraction, straight after the call.Added in version 2.0.0.
- Returns:
The route name, or
"none"if this thread has run no contraction.
- einsums.graph.load_graph_file(path: str) Graph#
Read
pathback as a runnable graph, throwing on failure.Added in version 2.0.0.
- Parameters:
path – The file to read.
- Returns:
The graph. The caller owns it; Python’s reference counting takes it from here.
- Raises:
Exception – With the failure’s message.
- einsums.graph.load_graph_file_into(path: str, registry: SpaceRegistry) Graph#
Read
pathback againstregistry, throwing on failure. The Python spelling.The counterpart of the
load_graphoverload taking aSpaceRegistry, for a caller who keeps their own registry rather than using the process-global one.The overload is named in prose rather than written out as a signature: a cross-reference followed immediately by a parameter list renders as an inline literal with an unterminated start-string, and the docs build treats that warning as an error.
Added in version 2.0.0.
- Parameters:
path – The file to read.
registry – The registry the file’s space NAMES resolve in. Must outlive the graph.
- Returns:
The graph, owned by the caller.
- Raises:
Exception – With every problem the file has.
- einsums.graph.make_approximation_record(pass_name: str, effect: ApproximationEffect, tolerance: float, bound: float, outputs: list[str] = std::vector<std::string>{}, spaces: list[str] = std::vector<std::string>{}, setup: str = "", origin: ApproximationOrigin = einsums::compute_graph::ApproximationOrigin::Asserted, measurement: str = "") ApproximationRecord#
Build an
ApproximationRecordin one call.A free function rather than a constructor, so
ApproximationRecordstays an AGGREGATE and C++ callers keep designated initializers, which is how a struct of seven fields stays readable at a call site. Declaring even a defaulted constructor would take that away. Python has no aggregate initialization and needs some entry point, and this is a better one than a default-constructed record with seven assignments after it.Added in version 2.0.0.
- Parameters:
pass_name – The pass applying the rewrite.
effect – What
boundis a bound on.tolerance – The knob the pass was asked for.
bound – The effect the pass states it had.
outputs – Manifest names the bound applies to; empty means all of them.
spaces – Index-space names the rewrite involved.
setup – Label of the setup node it created, or empty.
origin – Whether
boundwas computed or claimed.measurement – Name of the tensor carrying the measured error per bind, or empty.
- Returns:
The record.
- einsums.graph.make_index_space(name: str, scale_symbol: str, typical_extent: float = 0., growth: GrowthClass = einsums::compute_graph::GrowthClass::linear(), dim_symbol: str = std::string{}) IndexSpace#
Build an
IndexSpacefrom its parts.For callers without aggregate initialization (Python).
- Parameters:
name – Human-readable name, unique within a registry.
scale_symbol – Letter this space contributes to a symbolic cost polynomial.
typical_extent – Advisory extent. Zero, the default, means unset.
growth – How the extent grows with system size. Linear by default.
dim_symbol – Name a symbolic extent over this space goes by (“no”, “nv”, …). Empty, the default, when the space has none.
- Returns:
The space.
- einsums.graph.make_provenance_tag(name: str, attributes: list[tuple[str, str]]) ProvenanceTag#
Build a
ProvenanceTag.A named constructor rather than a real one, for the same reason
make_index_spaceis one:ProvenanceTagstays an aggregate so the library’s designated-initializer construction sites keep working, and this is what a caller with no aggregate initialization builds one through.Both parameters are required rather than the second defaulted, which is a binding constraint rather than a preference: the codegen renders a
= {}default as a bare brace-init that pybind’spy::argcannot be assigned from. The Python-side helper ineinsums.graphsupplies the empty list, so a caller there still writes just the name.Added in version 2.0.0.
- Parameters:
name – The vocabulary name.
attributes – Key/value pairs, possibly empty. Sorted by
Graph::annotate_tagon the way in, so the order given here does not matter.
- Returns:
The tag.
- einsums.graph.permute_view(parent: Any, perm: list[int]) RuntimeTensorView#
Python-friendly transpose / axis-permutation view.
Records a graph View whose result axis
ialiases parent axisperm[i](permmust be a permutation of[0, rank)). The returned view is graph-owned and aliases the parent. Unlike the rawRuntimeTensor.transpose_view(), which shares the parent’s data pointer and is invisible to the graph, a transposed tensor here can be fed to captured gemm/axpy/etc. ops. This is what backs the capture-awareA.T.with cg.capture(g): At = einsums.graph.permute_view(A, [1, 0]) # A.T, graph-registered einsums.linalg.gemm(1.0, At, B, 0.0, C)
- einsums.graph.plan_nary_einsum(spec: str, dims: list[list[int]], max_intermediate_elements: int = 0) list[NaryEinsumStep]#
The cheapest order to contract an einsum over several operands two at a time.
The order is the binary tree whose arithmetic, priced at these extents, is least: the same search and the same ranking the graph’s
MultiTermFactorizationuses on a captured product. Each partial product keeps only the letters a later step or the output still needs, so an index shared by the first two operands alone is summed when they are contracted.Added in version 2.0.0.
- Parameters:
spec – The spec, three or more operands; two are planned too, as one step.
dims – Each operand’s extents, in the spec’s order.
max_intermediate_elements – The most elements a partial product may hold, or zero for no limit. When no order keeps every partial product within it, the limit is dropped and the cheapest order is returned.
- Returns:
The steps, in the order to run them.
- Raises:
Exception – when the spec is malformed, names a different number of operands than
dimsholds, gives an operand the wrong rank, or a letter two different extents.
- einsums.graph.plan_nary_einsum_with_spaces(graph: Graph, spec: str, dims: list[list[int]], spaces: list[list[SpaceId]], max_intermediate_elements: int = 0) list[NaryEinsumStep]#
The cheapest order to contract an einsum’s operands, ranked by the index spaces they are annotated with.
plan_nary_einsumwith each letter bound to the space its axes are annotated with, by the rules a two-operand einsum binds its letters at capture, and ranked by the scalinggraph'sregistry declares: an order that is cheaper asymptotically wins even where these extents would favour another, asMultiTermFactorizationranks it. A letter no annotated axis carries is anonymous and ranked by its extent.Added in version 2.0.0.
- Parameters:
graph – The graph whose space registry the annotations belong to.
spec – The spec, three or more operands; two are planned too, as one step.
dims – Each operand’s extents, in the spec’s order.
spaces – Each operand’s per-axis spaces in the spec’s order, then C’s, each empty where the tensor is not annotated; or empty altogether.
max_intermediate_elements – As for
plan_nary_einsum.
- Returns:
The steps, in the order to run them.
- Raises:
Exception – as
plan_nary_einsumdoes, whenspacesdoes not hold one entry per operand and one for C, or when one letter is annotated with two different spaces.
- einsums.graph.save_graph_file(graph: Graph, path: str, allow_machine_dependent: bool = False) None#
Write
graphtopath, throwing on refusal.Added in version 2.0.0.
- Parameters:
graph – The graph to write.
path – Destination file.
allow_machine_dependent – Write the graph even when a structural-resource or tuning pass has changed it; see
SaveOptions::allow_machine_dependent.
- Raises:
Exception – With the refusal’s message.
- einsums.graph.stranded_materializations(graph: Graph) list[str]#
Graph-owned intermediates that are materialized and that nothing reads or writes.
The counterpart of
Materialization::num_unused, asked of a finished graph rather than of one run of the pass: a structural rewrite that dissolves an intermediate keeps its declaration, since a caller may still hold the handle, and allocating storage for it spends memory on a tensor whose whole point was to stop existing.Restricted to graph-owned intermediates on purpose. A caller-owned deferred tensor is one the caller may read after the graph runs, so allocating it is deliberate and not a finding.
A use is counted through aliases, so a tensor written only through a view of it counts as used.
- Parameters:
graph – The graph to audit; loop bodies, conditional branches and setup bodies are included.
- Returns:
The names, sorted, of every such tensor.
- einsums.graph.tile_view(parent: Any, coord: list[int]) RuntimeTensorView#
Record a dense, parent-aliasing view of a single tile.
The tiled capture-view primitive. A tile is a full-rank dense block, so the returned
RuntimeTensorViewfeeds the ENTIRE dense op surface - einsum, gemm, permute, axpby, … - inside capture, which is exactly how tiled workflows iterate (per tile block, the shape TiledExpansion itself lowers to). Element-granular slicing of a tiled tensor is deliberately not offered: a slice crossing tile boundaries has no single buffer.The tile is created (deferred, dims fixed by the grid) at capture if absent - value-equivalent, since absent tiles are rigorous zeros and a created tile materializes zeroed. Each replay the executor re-resolves the tile from the LIVE parent and re-emplaces the view, so parents whose storage moves between replays (graph-owned deferred scratch released by FreeInsertion and re-materialized) stay correct.
The recorded ViewDescriptor carries one constant
[c, c+1)range per axis IN TILE UNITS: the disjointness-aware hazard scan then proves views of distinct tiles non-conflicting, so per-tile writes to one output can be scheduled concurrently. Units stay consistent because element-unit boxes cannot appear on a tiled parent (the dense view entry points do not accept one).with cg.capture(g): for i in range(2): a = cg.tile_view(A, [i, 0]) c = cg.tile_view(C, [i, 0]) einsums.einsum("ij <- ik ; kj", c, a, B, c_pf=0.0, ab_pf=1.0)
- einsums.graph.tiles(sizes: list[int]) SpaceTiling#
A tiled axis with a partition and no space.
The tiled counterpart of
fixed: an axis that is cut up but means nothing chemically, so it gets no space and no dim symbol and a bind may not move it.Added in version 2.0.0.
- Parameters:
sizes – The tile sizes.
- Returns:
The axis.
- einsums.graph.validate_graph_ir_file(path: str) None#
Check
path, throwing with every problem when it is not valid.Added in version 2.0.0.
- Parameters:
path – The file to check.
- Raises:
Exception – With one line per problem found.
- einsums.graph.view(parent: Any, ranges: list[tuple[int, int]]) RuntimeTensorView#
Python-friendly wrapper over
view_runtime.Takes a list of
(lo, hi)integer pairs, one per parent axis. A pair with both values < 0 (the conventional(-1, -1)) means “full axis”; any other pair becomes a[lo, hi)range slice.Must be called inside a capture context. The returned view is owned by the active graph and aliases the parent: writes through it land in the parent, and the graph’s optimization passes treat it as a dependency on the parent.
with cg.capture(g): C_occ = einsums.graph.view(C, [(-1, -1), (0, nocc)]) # C[:, :nocc] einsums.linalg.gemm(2.0, C_occ, C_occ, 0.0, D, trans_b=True)
- einsums.graph.view_indexed(parent: Any, specs: list[tuple[int, int, int]]) RuntimeTensorView#
Python-friendly indexed view supporting rank-reducing integer indices.
One
(kind, a, b)triple per parent axis:kind == 0: full axis (a/bignored)kind == 1: range[a, b)kind == 2: drop, indexing the axis ataand removing it from the result Result rank = parent rank − (number of drop axes). This is what backs capture-mode rank-reducing reads likeA[i]/A[:, j](the plainviewabove only does full/range, i.e. rank-preserving slices).
- einsums.graph.views(parent: Any, specs: list[list[tuple[int, int, int]]]) list[RuntimeTensorView]#
Batched
view_indexed_python: record N views of one parent in one call.Same per-axis
(kind, a, b)triples asview_indexed-0full,1range[a, b),2drop ata- one inner list per view, and the views come back in the order they were asked for.This exists for callers that build many views of the same parent in a loop, which is the shape of every batched capture: slicing per-pair blocks out of a pair store issues thousands of these, and the per-call Python and pybind overhead - argument normalization, overload resolution, the crossing itself - was about a third of what each view cost. One crossing for N views leaves only the recording. The recorded graph is identical to N
view_indexedcalls; nothing downstream can tell the difference.
Enumerations#
- class einsums.graph.ApproximationEffect#
What a lossy pass’s tolerance is a bound ON.
A number without units is not a bound, and the three kinds below do not convert into one another: an element-wise bound says nothing about a norm, and a norm bound says nothing about the worst element. So a record carries which one it means and composition happens within a kind, never across.
Records of different kinds coexist on one output rather than being refused. There is nothing that needs them as a single number:
Graph::accuracy_spentcounts one kind at a time andApproximationTolerancereports the two sides separately, which is the honest description of a result that is off by so much in norm and so much per element. A declared BUDGET is the exception, because a budget claims to be a cap and can only cap its own units; seeGraph::can_approximate.See also
ApproximationRecord
See also
compose_approximation
Added in version 2.0.0.
- ElementWise = 0#
Worst absolute difference over the elements of the named outputs.
- NormRelative = 1#
Difference in norm, RELATIVE to the exact result’s norm.
- EnergyLike = 2#
Absolute error in a scalar the outputs reduce to, an energy being the case this exists for. Composes with
ElementWise, since both are absolute.
- class einsums.graph.ApproximationOrigin#
Where a bound’s number came from.
A bound and a guess are the same double, and months later a reader of a saved graph cannot tell them apart from the number alone. They deserve different trust, so the file carries which it is.
Assertedis not a lesser answer, it is the only one available wherever measuring would mean computing the exact result the approximation exists to avoid computing. A metric fit is that case: its error is the difference from the exact tensor, and a caller holding that had no reason to fit.Measuredbelongs to a provider that genuinely knows, a truncated decomposition holding its own discarded singular values being the plain example.Added in version 2.0.0.
- Measured = 0#
The pass computed the error it actually had.
- Asserted = 1#
A caller stated the error, and nothing here checked it.
- class einsums.graph.BisectMode#
How many passes a trial turns on at once.
- Individual = 0#
One pass per trial. Answers “which pass is wrong on its own”, which is the question the design states and the one a deterministic recognizer can fail.
- Cumulative = 1#
Passes one through k. Answers a different question, “which pass is wrong AFTER the ones before it”, and it is a real one: a pass can be correct alone and wrong on a node set an earlier pass rewrote, which is the failure mode a phase with three re-associating members invites and which
BisectMode::Individualcannot see.
- class einsums.graph.ChainPricing#
What ContractionPlanning prices a bracketing against.
- Auto = 0#
The detected machine’s
CostModel. The default.
- Flops = 1#
CostModel::flop_count: flops alone, the same answer on every < machine. For tests that must know whether a chain is re-bracketed, < which on small shapes the detected model decides by its per-call < overheads, and so differently from one machine to the next.
- class einsums.graph.CrossSpaceSeverity#
How much a
CrossSpaceFindingis worth acting on.- Note = 0#
Legitimate, listed for the record: a restriction of one space to a subspace.
- Warning = 1#
Nothing declared settles whether the two spaces overlap.
- Error = 2#
The two spaces are declared disjoint, so the contraction is identically zero.
- class einsums.graph.DecisionKind#
Whether a pass applied something, declined a candidate, or only had something to say.
Added in version 2.0.0.
- Applied = 0#
The pass changed the graph, or chose something it reports.
- Declined = 1#
The pass looked at a candidate and left it, for a reason.
- Note = 2#
Something the pass reported that is neither.
- class einsums.graph.EventKind#
What an
ExecutionEventreports.Added in version 2.0.0.
- ReplayStart = 0#
The outermost replay began.
- NodeStart = 1#
A node began, on the thread that runs it.
- NodeEnd = 2#
That node finished, or threw.
- Read = 3#
A slab, box or whole tensor was read from a backing’s storage.
- Write = 4#
One was written to it.
- Publish = 5#
An update backing’s new value was made current.
- ReplayEnd = 6#
The outermost replay finished.
- class einsums.graph.Factor#
Whether to let the cost model decide that a group is worth factoring.
- Auto = 0#
Price the trade against the
CostModel. The default.
- Always = 1#
Factor whenever the rewrite is structurally possible, whatever it < costs. For tests that exercise the rewrite on shapes too small to < be worth it, and for callers who know their workload better than < the model does.
- class einsums.graph.OpKind#
Identifies the kind of operation a node represents.
Used by optimization passes for pattern matching. For example, ScaleAbsorption looks for OpKind::Scale followed by a prefactor-bearing op.
Categories:
TensorAlgebra: Einsum, Permute, Transpose, ElementTransform, KhatriRao
BLAS-level: Gemm, Gemv, Ger, Dot, Scale, Axpby, DirectProduct
LAPACK-level: SVD, QR, Syev, Heev, Geev, Gesv, Getrf, Getrs, Invert, Det, Pow, etc.
Other: HPTTPermute, Custom
- Einsum = 0#
Tensor contraction from a string spec, via dispatch::string_einsum()
- Permute = 1#
Index reordering from a string spec, via dispatch::string_permute_impl()
- GroupedPermute = 2#
Many independent index reorderings, one per member
- Transpose = 3#
2D transpose, via tensor_permute::transpose()
- ElementTransform = 4#
Element-wise unary transform
- KhatriRao = 5#
Khatri-Rao product
- BatchedGemm = 6#
Many independent GEMMs in one gemm_batch call
- GroupedBatchedGemm = 7#
Many independent GEMMs of DIFFERING shape in one gemm_batch_grouped call
- Gemm = 8#
General matrix-matrix multiply (BLAS Level 3)
- Gemv = 9#
General matrix-vector multiply (BLAS Level 2)
- Ger = 10#
Rank-1 update (BLAS Level 2)
- Dot = 11#
Dot product (returns scalar)
- GroupedDot = 12#
Many independent dot products, one per entry, in one node
- Scale = 13#
Scalar multiplication of entire tensor
- Axpby = 14#
Y = alpha * X + beta * Y
- GroupedAxpby = 15#
Many independent Y = alpha*X + beta*Y, one per entry, in one node
- GroupedSandwich = 16#
Many independent q-tiled dressed sandwich accumulations, one per entry
- GroupedGatherRotate = 17#
Many independent q-tiled gather-and-rotate blocks, one per entry
- DirectProduct = 18#
Element-wise (Hadamard) product
- DirectDivision = 19#
Element-wise (Hadamard) quotient
- GroupedDirectProduct = 20#
Many independent element-wise products, one per member
- GroupedDirectDivision = 21#
Many independent element-wise quotients, one per member
- SVD = 22#
Singular value decomposition
- SVD_DD = 23#
SVD with divide-and-conquer algorithm
- TruncatedSVD = 24#
Truncated SVD (keeping k singular values)
- QR = 25#
QR decomposition
- Syev = 26#
Symmetric eigendecomposition
- Heev = 27#
Hermitian eigendecomposition
- Geev = 28#
General eigendecomposition
- TruncatedSyev = 29#
Truncated symmetric eigendecomposition
- Gesv = 30#
General linear system solver (AX = B)
- Getrf = 31#
LU factorization
- Getrs = 32#
Solve against an LU factorization
- Getri = 33#
Inverse from LU factorization
- Invert = 34#
Matrix inverse
- Pseudoinverse = 35#
Moore-Penrose pseudoinverse
- Det = 36#
Matrix determinant (returns scalar)
- Pow = 37#
Matrix power
- SymmGemm = 38#
Symmetric double multiply: C = B^T * A * B
- Norm = 39#
Tensor norm (returns scalar)
- SolveLyapunov = 40#
Continuous Lyapunov equation solver
- HPTTPermute = 41#
High-performance tensor transpose
- Conditional = 42#
If-then-else branch with subgraphs
- Loop = 43#
While/for loop with body subgraph
- Setup = 44#
Body computed once per bound problem, skipped by later replays
- LaplaceQuadrature = 45#
Laplace-transform points, weights and per-axis exponentials, refit per bind
- Alloc = 46#
Tensor allocation (marks lifetime start)
- Free = 47#
Tensor deallocation (marks lifetime end)
- HostToDevice = 48#
Transfer tensor from host to device memory
- DeviceToHost = 49#
Transfer tensor from device to host memory
- ParallelFor = 50#
Data-parallel for loop (delegates to TaskPool)
- ParallelReduce = 51#
Data-parallel reduce (delegates to TaskPool)
- DiskRead = 52#
Read tensor data from disk (HDF5, binary, etc.)
- DiskWrite = 53#
Write tensor data to disk (checkpointing)
- Materialize = 54#
Allocate storage for a deferred (shell) tensor
- Initialize = 55#
Fill tensor with initial values (zero, random, disk)
- View = 56#
Non-owning slice/view of another tensor (zero-copy alias)
- WriteParam = 57#
Write the value of a scalar tensor into a Pipeline parameter
- Trace = 58#
Diagonal sum of a square rank-2 tensor (returns scalar)
- Allreduce = 59#
Sum partial results across MPI ranks
- Broadcast = 60#
Root sends data to all ranks
- Allgather = 61#
Each rank contributes a piece, all receive the whole
- Scatter = 62#
Root distributes pieces to ranks
- Barrier = 63#
Synchronization point across ranks
- TileGather = 64#
Copy a tiled tensor’s tiles into one dense buffer
- TileScatter = 65#
Copy a dense buffer back into a tiled tensor’s tiles
- TileElementwise = 66#
Apply one elementwise operation to a whole list of tiles
- DiisStep = 67#
Pulay DIIS extrapolation over an accelerator’s (amplitude, step) pairs
- Custom = 68#
User-registered custom operation
- class einsums.graph.Tristate#
Answer to a relation query that may simply not be known.
The registry knows only what was declared and what follows; a rewriting pass treats Unknown as No.
- No = 0#
The relation is known not to hold.
- Yes = 1#
The relation is known to hold.
- Unknown = 2#
Nothing declared or derivable settles the question.