einsums#
Note
This page is generated by apiary from the binding
annotations and the package’s Python source. Do not edit by hand.
Summary#
RuntimeTensorF— Represents a tensor whose properties can be determined at runtime but not compile time.RuntimeTensorD— Represents a tensor whose properties can be determined at runtime but not compile time.RuntimeTensorC— Represents a tensor whose properties can be determined at runtime but not compile time.RuntimeTensorZ— Represents a tensor whose properties can be determined at runtime but not compile time.IndexSpace— A per-irrep selection of indices along one axis of a tiled tensor.MemoryPool— A pre-reserved region of memory that mimalloc manages exclusively.MemoryPoolEpoch— RAII scope whose carves are released together when it closes.RuntimeTensorViewF— Represents a view of a tensor whose properties can be determined at runtime but not compile time.RuntimeTensorViewD— Represents a view of a tensor whose properties can be determined at runtime but not compile time.RuntimeTensorViewC— Represents a view of a tensor whose properties can be determined at runtime but not compile time.RuntimeTensorViewZ— Represents a view of a tensor whose properties can be determined at runtime but not compile time.SymmetryDescriptor— Describes the symmetry of a tensor as a set of generators.SymmetryOp— One generator of a tensor’s symmetry group.TiledRuntimeTensorF— A runtime-rank, tile-wise sparse tensor.TiledRuntimeTensorD— A runtime-rank, tile-wise sparse tensor.TiledRuntimeTensorC— A runtime-rank, tile-wise sparse tensor.TiledRuntimeTensorZ— A runtime-rank, tile-wise sparse tensor.TiledRuntimeTensorViewF— A non-owning, per-irrep-sliced view of aTiledRuntimeTensor.TiledRuntimeTensorViewD— A non-owning, per-irrep-sliced view of aTiledRuntimeTensor.TiledRuntimeTensorViewC— A non-owning, per-irrep-sliced view of aTiledRuntimeTensor.TiledRuntimeTensorViewZ— A non-owning, per-irrep-sliced view of aTiledRuntimeTensor.create_identity_tensor— Create a runtime-rank identity tensor from a runtime shape vector.create_random_definite— Python-bindable runtime-rank create_random_definite.create_random_semidefinite— Python-bindable runtime-rank create_random_semidefinite.create_random_tensor— Python-bindable runtime-rank create_random_tensor.create_zero_tensor— Create a runtime-rank zero tensor from a runtime shape vector.einsum— Graph-aware einsum: contract A and B according tospec.get_log_level— Return the current runtime log level on the einsums logger.is_running— Test whether the runtime system is currently running.make_temp_path— Generate a unique path in the system temporary directory.permute— Graph-aware permute with explicit prefactors.pool_empty— Python entry point forpool_empty.pool_reserve_cost— The arena bytes a reservation ofbytesactually claims, headroom and rounding included. Planners budgeting against einsums:max-memory should charge this, not the raw sum.pool_zeros— Python entry point forpool_zeros.seed_random— Set the seed of the random number generator.set_log_level— Set the runtime log level on the einsums logger.OptLevel— Optimization level for Graph::optimize(), compiler-style.RuntimeState— Holds the possible states for the runtime.
Classes#
- class einsums.RuntimeTensorF#
Represents a tensor whose properties can be determined at runtime but not compile time.
Mostly for the Python interface. For rank-templated calls, convert it to a TensorView.
Added in version 1.0.0.
Changed in version 2.0.0: This used to be RuntimeTensor. An allocator parameter was added, and RuntimeTensor is now an alias to this with the standard allocator.
- __init__() None#
- __init__(name: str, dims: Any) None
Create a new runtime tensor with the given name and dimensions.
- Parameters:
name – the new name of the tensor.
dims – The dimensions of the tensor.
- set_all(val: Any) None#
Set all of the data in the tensor to the same value.
Not supported on device runtime tensors; throws at runtime. (set_all is virtual, so its body is instantiated for the v-table even if never called; we branch with if constexpr instead of static_assert to keep the device variant compilable.)
- Parameters:
val – The value to fill the tensor with.
- dim(d: int) int#
Get the length of the tensor along a given axis.
- Parameters:
d – The axis to query. Negative values will wrap around.
- stride(d: int) int#
Get the stride along a given axis.
- Parameters:
d – The axis to query. Negative values will wrap around.
- transpose_view() RuntimeTensorView#
- set_symmetry(desc: SymmetryDescriptor) None#
Declare the symmetry the tensor’s values have. A promise, not a check: a graph that computes half of a contraction from it checks it before relying on it, and nothing else does. An empty descriptor clears the declaration.
- __getitem__(key: int | slice | Any) object#
Subscript access (NumPy-style). A full integer index returns a scalar; partial, slice, or ellipsis indices return a view. Synthesized from the index protocol.
- __setitem__(key: int | slice | Any, value: object) None#
Assign to a scalar element or sub-view. Synthesized from the index protocol.
- __iter__() Iterator#
Iterate over the tensor’s elements in storage order. Synthesized from the iterator protocol.
- size: int#
Returns the linear size of the tensor.
The element count implied by the dims, which is what materialize() allocates. Not the owned buffer’s length: alias_to() and materialize_into() empty the owned buffer while the tensor is fully usable, so reporting that buffer’s size gave 0 for aliased and arena-backed tensors. A deferred tensor reports the count it will have once materialized; use is_materialized() to ask whether storage exists.
(read-only)
- class einsums.RuntimeTensorD#
Represents a tensor whose properties can be determined at runtime but not compile time.
Mostly for the Python interface. For rank-templated calls, convert it to a TensorView.
Added in version 1.0.0.
Changed in version 2.0.0: This used to be RuntimeTensor. An allocator parameter was added, and RuntimeTensor is now an alias to this with the standard allocator.
- __init__() None#
- __init__(name: str, dims: Any) None
Create a new runtime tensor with the given name and dimensions.
- Parameters:
name – the new name of the tensor.
dims – The dimensions of the tensor.
- set_all(val: Any) None#
Set all of the data in the tensor to the same value.
Not supported on device runtime tensors; throws at runtime. (set_all is virtual, so its body is instantiated for the v-table even if never called; we branch with if constexpr instead of static_assert to keep the device variant compilable.)
- Parameters:
val – The value to fill the tensor with.
- dim(d: int) int#
Get the length of the tensor along a given axis.
- Parameters:
d – The axis to query. Negative values will wrap around.
- stride(d: int) int#
Get the stride along a given axis.
- Parameters:
d – The axis to query. Negative values will wrap around.
- transpose_view() RuntimeTensorView#
- set_symmetry(desc: SymmetryDescriptor) None#
Declare the symmetry the tensor’s values have. A promise, not a check: a graph that computes half of a contraction from it checks it before relying on it, and nothing else does. An empty descriptor clears the declaration.
- __getitem__(key: int | slice | Any) object#
Subscript access (NumPy-style). A full integer index returns a scalar; partial, slice, or ellipsis indices return a view. Synthesized from the index protocol.
- __setitem__(key: int | slice | Any, value: object) None#
Assign to a scalar element or sub-view. Synthesized from the index protocol.
- __iter__() Iterator#
Iterate over the tensor’s elements in storage order. Synthesized from the iterator protocol.
- size: int#
Returns the linear size of the tensor.
The element count implied by the dims, which is what materialize() allocates. Not the owned buffer’s length: alias_to() and materialize_into() empty the owned buffer while the tensor is fully usable, so reporting that buffer’s size gave 0 for aliased and arena-backed tensors. A deferred tensor reports the count it will have once materialized; use is_materialized() to ask whether storage exists.
(read-only)
- class einsums.RuntimeTensorC#
Represents a tensor whose properties can be determined at runtime but not compile time.
Mostly for the Python interface. For rank-templated calls, convert it to a TensorView.
Added in version 1.0.0.
Changed in version 2.0.0: This used to be RuntimeTensor. An allocator parameter was added, and RuntimeTensor is now an alias to this with the standard allocator.
- __init__() None#
- __init__(name: str, dims: Any) None
Create a new runtime tensor with the given name and dimensions.
- Parameters:
name – the new name of the tensor.
dims – The dimensions of the tensor.
- set_all(val: Any) None#
Set all of the data in the tensor to the same value.
Not supported on device runtime tensors; throws at runtime. (set_all is virtual, so its body is instantiated for the v-table even if never called; we branch with if constexpr instead of static_assert to keep the device variant compilable.)
- Parameters:
val – The value to fill the tensor with.
- dim(d: int) int#
Get the length of the tensor along a given axis.
- Parameters:
d – The axis to query. Negative values will wrap around.
- stride(d: int) int#
Get the stride along a given axis.
- Parameters:
d – The axis to query. Negative values will wrap around.
- transpose_view() RuntimeTensorView#
- set_symmetry(desc: SymmetryDescriptor) None#
Declare the symmetry the tensor’s values have. A promise, not a check: a graph that computes half of a contraction from it checks it before relying on it, and nothing else does. An empty descriptor clears the declaration.
- __getitem__(key: int | slice | Any) object#
Subscript access (NumPy-style). A full integer index returns a scalar; partial, slice, or ellipsis indices return a view. Synthesized from the index protocol.
- __setitem__(key: int | slice | Any, value: object) None#
Assign to a scalar element or sub-view. Synthesized from the index protocol.
- __iter__() Iterator#
Iterate over the tensor’s elements in storage order. Synthesized from the iterator protocol.
- size: int#
Returns the linear size of the tensor.
The element count implied by the dims, which is what materialize() allocates. Not the owned buffer’s length: alias_to() and materialize_into() empty the owned buffer while the tensor is fully usable, so reporting that buffer’s size gave 0 for aliased and arena-backed tensors. A deferred tensor reports the count it will have once materialized; use is_materialized() to ask whether storage exists.
(read-only)
- class einsums.RuntimeTensorZ#
Represents a tensor whose properties can be determined at runtime but not compile time.
Mostly for the Python interface. For rank-templated calls, convert it to a TensorView.
Added in version 1.0.0.
Changed in version 2.0.0: This used to be RuntimeTensor. An allocator parameter was added, and RuntimeTensor is now an alias to this with the standard allocator.
- __init__() None#
- __init__(name: str, dims: Any) None
Create a new runtime tensor with the given name and dimensions.
- Parameters:
name – the new name of the tensor.
dims – The dimensions of the tensor.
- set_all(val: Any) None#
Set all of the data in the tensor to the same value.
Not supported on device runtime tensors; throws at runtime. (set_all is virtual, so its body is instantiated for the v-table even if never called; we branch with if constexpr instead of static_assert to keep the device variant compilable.)
- Parameters:
val – The value to fill the tensor with.
- dim(d: int) int#
Get the length of the tensor along a given axis.
- Parameters:
d – The axis to query. Negative values will wrap around.
- stride(d: int) int#
Get the stride along a given axis.
- Parameters:
d – The axis to query. Negative values will wrap around.
- transpose_view() RuntimeTensorView#
- set_symmetry(desc: SymmetryDescriptor) None#
Declare the symmetry the tensor’s values have. A promise, not a check: a graph that computes half of a contraction from it checks it before relying on it, and nothing else does. An empty descriptor clears the declaration.
- __getitem__(key: int | slice | Any) object#
Subscript access (NumPy-style). A full integer index returns a scalar; partial, slice, or ellipsis indices return a view. Synthesized from the index protocol.
- __setitem__(key: int | slice | Any, value: object) None#
Assign to a scalar element or sub-view. Synthesized from the index protocol.
- __iter__() Iterator#
Iterate over the tensor’s elements in storage order. Synthesized from the iterator protocol.
- size: int#
Returns the linear size of the tensor.
The element count implied by the dims, which is what materialize() allocates. Not the owned buffer’s length: alias_to() and materialize_into() empty the owned buffer while the tensor is fully usable, so reporting that buffer’s size gave 0 for aliased and arena-backed tensors. A deferred tensor reports the count it will have once materialized; use is_materialized() to ask whether storage exists.
(read-only)
- class einsums.IndexSpace#
A per-irrep selection of indices along one axis of a tiled tensor.
Each axis of a
TiledRuntimeTensoris partitioned into per-irrep blocks. An IndexSpace picks a half-open[start, stop)sub-range out of each irrep’s block, so a single IndexSpace can describe e.g. “the occupied orbitals” ([0, nocc_h)in every irreph) or “the virtuals” ([nocc_h, nmo_h)). Slicing a tiled tensor with one IndexSpace per axis (A.view({o, v, o, v})) yields aTiledRuntimeTensorView.Added in version 2.0.0.
- class einsums.MemoryPool#
A pre-reserved region of memory that mimalloc manages exclusively.
An exclusive mimalloc arena plus a heap bound to it. A carve takes about a microsecond for a multi-megabyte block, against tens to hundreds for an mmap, and a free returns the bytes at once. When the arena runs out the pool reserves another and warns, rather than throwing in a kernel.
allocatemust run on the constructing thread (it throws otherwise); freeing may happen on any. Arenas are capped per process and never returned to the OS, so keep pools few, long-lived and reserved to their peak size up front.Added in version 2.0.0.
- __init__(reserve_bytes: int, name: str = 'pool', warn_bytes: int = 0, pinned: bool = False) None#
Reserve a pool.
Added in version 2.0.0.
- Parameters:
reserve_bytes – Bytes the caller expects to carve; the arena adds headroom.
name – Label used in log messages.
warn_bytes – Usage that logs a one-shot warning; zero disables it.
pinned – Keep freed pages resident, so recarves are fault-free but the pool never shrinks below its high water. For small, hot scratch pools only; unpinned pages purge back to the OS.
- Raises:
Exception – if the arena cannot be reserved.
- reserve(bytes: int) None#
Grow the pool so at least
bytesof capacity are reserved.A no-op when already that large. Reserve once rather than in steps: each growth costs an arena, and arenas are capped and never reclaimed.
Added in version 2.0.0.
- reset() None#
Bulk-free everything the pool holds and start over.
Added in version 2.0.0.
- Raises:
Exception – if any keepalive token is outstanding, or if an epoch is open.
- epoch() MemoryPoolEpoch#
Open a nested scope; see
MemoryPoolEpoch.
- class einsums.MemoryPoolEpoch#
RAII scope whose carves are released together when it closes.
Each epoch gets a heap of its own inside the pool’s arena, so closing it bulk-frees every carve made inside it, including ones nothing tracked. Epochs nest and must close in reverse order of opening.
If a keepalive token carved in the scope is still held,
closethrows (Python’swithtakes this path), while the destructor logs an error and moves the surviving blocks to the pool’s base heap, where they stay valid until their tokens die.Added in version 2.0.0.
- class einsums.RuntimeTensorViewF#
Represents a view of a tensor whose properties can be determined at runtime but not compile time.
Like GeneralRuntimeTensor, this kind of view is unable to be used in many of the same ways as a tensor with compile-time rank, and is mostly used for communication with the Python interface. To use it with rank-templated Einsums calls, convert it into a TensorView so that the rank can be coerced at compile time.
- dim(d: int) int#
Get the length of the tensor along the given axis.
- Parameters:
d – The axis to query. Negative indices will be wrapped around.
- stride(d: int) int#
Gets the stride of the tensor along the given axis.
- Parameters:
d – The axis to query. Negative indices will be wrapped around.
- transpose_view() RuntimeTensorView#
- __getitem__(key: int | slice | Any) object#
Subscript access (NumPy-style). A full integer index returns a scalar; partial, slice, or ellipsis indices return a view. Synthesized from the index protocol.
- class einsums.RuntimeTensorViewD#
Represents a view of a tensor whose properties can be determined at runtime but not compile time.
Like GeneralRuntimeTensor, this kind of view is unable to be used in many of the same ways as a tensor with compile-time rank, and is mostly used for communication with the Python interface. To use it with rank-templated Einsums calls, convert it into a TensorView so that the rank can be coerced at compile time.
- dim(d: int) int#
Get the length of the tensor along the given axis.
- Parameters:
d – The axis to query. Negative indices will be wrapped around.
- stride(d: int) int#
Gets the stride of the tensor along the given axis.
- Parameters:
d – The axis to query. Negative indices will be wrapped around.
- transpose_view() RuntimeTensorView#
- __getitem__(key: int | slice | Any) object#
Subscript access (NumPy-style). A full integer index returns a scalar; partial, slice, or ellipsis indices return a view. Synthesized from the index protocol.
- class einsums.RuntimeTensorViewC#
Represents a view of a tensor whose properties can be determined at runtime but not compile time.
Like GeneralRuntimeTensor, this kind of view is unable to be used in many of the same ways as a tensor with compile-time rank, and is mostly used for communication with the Python interface. To use it with rank-templated Einsums calls, convert it into a TensorView so that the rank can be coerced at compile time.
- dim(d: int) int#
Get the length of the tensor along the given axis.
- Parameters:
d – The axis to query. Negative indices will be wrapped around.
- stride(d: int) int#
Gets the stride of the tensor along the given axis.
- Parameters:
d – The axis to query. Negative indices will be wrapped around.
- transpose_view() RuntimeTensorView#
- __getitem__(key: int | slice | Any) object#
Subscript access (NumPy-style). A full integer index returns a scalar; partial, slice, or ellipsis indices return a view. Synthesized from the index protocol.
- class einsums.RuntimeTensorViewZ#
Represents a view of a tensor whose properties can be determined at runtime but not compile time.
Like GeneralRuntimeTensor, this kind of view is unable to be used in many of the same ways as a tensor with compile-time rank, and is mostly used for communication with the Python interface. To use it with rank-templated Einsums calls, convert it into a TensorView so that the rank can be coerced at compile time.
- dim(d: int) int#
Get the length of the tensor along the given axis.
- Parameters:
d – The axis to query. Negative indices will be wrapped around.
- stride(d: int) int#
Gets the stride of the tensor along the given axis.
- Parameters:
d – The axis to query. Negative indices will be wrapped around.
- transpose_view() RuntimeTensorView#
- __getitem__(key: int | slice | Any) object#
Subscript access (NumPy-style). A full integer index returns a scalar; partial, slice, or ellipsis indices return a view. Synthesized from the index protocol.
- class einsums.SymmetryDescriptor#
Describes the symmetry of a tensor as a set of generators.
The group is the generators’ closure; only the generators are stored (ERIs need three).
Common patterns
SymmetryDescriptor::symmetric_pair(i, j):T(..,i,..,j,..) = T(..,j,..,i,..).SymmetryDescriptor::antisymmetric_pair(i, j): negated on swap.SymmetryDescriptor::hermitian_pair(i, j): symmetric plus complex conjugate.SymmetryDescriptor::eri_8fold(): 8-fold ERI symmetry in chemists’ notation.SymmetryDescriptor::ccsd_t2(): antisym in (0,1) and antisym in (2,3).
Tolerance
Floating-point arithmetic drifts away from exact symmetry.
toleranceis the maximum absolute element-wise deviation thatcheck_symmetry()accepts as “still symmetric.”- __init__() None#
- __init__(gens: list[SymmetryOp], tol: float = 9.9999999999999998E-13) None
A descriptor from its generators, and the deviation
toleranceaccepts.
- static symmetric_pair(a: int, b: int) SymmetryDescriptor#
Symmetric in a single index pair:
T(..,a,..,b,..) = T(..,b,..,a,..).
- static antisymmetric_pair(a: int, b: int) SymmetryDescriptor#
Antisymmetric in a single index pair:
T(..,a,..,b,..) = -T(..,b,..,a,..).
- static hermitian_pair(a: int, b: int) SymmetryDescriptor#
Hermitian in a single index pair (complex tensors):
T(..,a,..,b,..) = conj(T(..,b,..,a,..)).
- static anti_hermitian_pair(a: int, b: int) SymmetryDescriptor#
Anti-Hermitian / skew-Hermitian:
T(..,a,..,b,..) = -conj(T(..,b,..,a,..)).
- static eri_8fold() SymmetryDescriptor#
8-fold symmetry of real two-electron integrals in chemists’ notation
(μν|λσ) = (νμ|λσ) = (μν|σλ) = (νμ|σλ) = (λσ|μν) = (σλ|μν) = (λσ|νμ) = (σλ|νμ). The three generators are: swap(0,1), swap(2,3), group_swap({0,1},{2,3}).
- static eri_4fold() SymmetryDescriptor#
4-fold symmetry of complex two-electron integrals: two real-pair swaps, no bra/ket swap (which would also complex-conjugate).
- static ccsd_t2() SymmetryDescriptor#
CCSD T2 amplitudes
T[a,b,i,j]: antisym in virtual pair (0,1) and antisym in occupied pair (2,3), soT[a,b,i,j] = -T[b,a,i,j] = -T[a,b,j,i] = T[b,a,j,i].
- class einsums.SymmetryOp#
One generator of a tensor’s symmetry group.
permutation[i]is the new position of the index that currently sits at positioni. For a tensorT(i0, i1, ...)the operation mapsT(i0, i1, ...) -> sign * T(i_{perm[0]}, i_{perm[1]}, ...). For the Hermitian case the right-hand side is additionally complex-conjugated.Padding: for tensors of rank <
kMaxSymmetryRankthe unused trailing positions must be filled with their natural index (permutation[i] = i).- static identity() SymmetryOp#
Identity operation: all positions map to themselves.
- class einsums.TiledRuntimeTensorF#
A runtime-rank, tile-wise sparse tensor.
This is the runtime-rank analogue of
TiledTensor. WhereTiledTensorcarries its rank as a compile-time template parameter (and therefore keys its tiles bystd::array<int, Rank>), TiledRuntimeTensor stores its rank at runtime and keys tiles bystd::vector<int>. Each populated tile is a denseRuntimeTensor(which reusesdetail::TensorImplfor its runtime-rank dims/strides machinery); absent tiles are rigorously zero and are not stored.Like
TiledTensorthis models a general tiled layout: a tile may sit anywhere on the grid (not only the diagonal) and may be rectangular. The block-diagonal, square-tile special case is whatBlockTensorcaptures; the off-diagonal / rectangular cases (e.g. a non-totally-symmetric operator coupling different symmetry sectors) require this general form.ComputeGraph integration (Tier A)
This type satisfies
CoreBasicTensorConceptso it can be captured into a ComputeGraph for lifecycle orchestration (materialize / release / zero) and passed around as an operand handle. Because a multi-tile tensor has no single contiguous backing buffer,data()returnsnullptrfor the multi-tile case (and the single tile’s pointer in the degenerate one-cell grid), and the type advertises itself viais_tiled_tensor()so the graph can flag the handle (TensorHandle::is_tiled) and keep it out of dense buffer-level code paths. Tiled contraction inside the graph is intentionally not provided here.Added in version 2.0.0.
- dim(d: int) int#
Global extent along axis
d(sum of that axis’s tile sizes). Supports Python-style negative indexing.
- grid_size() int#
Number of grid cells (product of the per-axis tile counts). This is the number of possible tiles, not the number populated.
- add_tile(coord: list[int]) None#
Declare a tile at
coord. The declaration is deferred, with no storage allocated.Creates a shell
RuntimeTensorwith the right dims for that grid cell but no backing data. The tile is allocated later bymaterialize(or by the ComputeGraph MaterializationPass). No-op if the tile already exists.- Parameters:
coord – The grid coordinate, one index per axis.
- tile_view(coord: list[int]) RuntimeTensorView#
Python-facing tile accessor: materialize the tile at
coord(creating it if absent) and return a numpy-backed view of it. KEEP_ALIVE(0,1) ties this tensor’s lifetime to the returned view, so the tile’s storage outlives any numpy array Python builds from it.
- view(spaces: list[IndexSpace]) TiledRuntimeTensorView#
Create a non-owning
TiledRuntimeTensorViewrestricted to oneIndexSpaceper axis (e.g.A.view({o, v, o, v})). The view keeps this tensor alive; defined out-of-line below TiledRuntimeTensorView.
- class einsums.TiledRuntimeTensorD#
A runtime-rank, tile-wise sparse tensor.
This is the runtime-rank analogue of
TiledTensor. WhereTiledTensorcarries its rank as a compile-time template parameter (and therefore keys its tiles bystd::array<int, Rank>), TiledRuntimeTensor stores its rank at runtime and keys tiles bystd::vector<int>. Each populated tile is a denseRuntimeTensor(which reusesdetail::TensorImplfor its runtime-rank dims/strides machinery); absent tiles are rigorously zero and are not stored.Like
TiledTensorthis models a general tiled layout: a tile may sit anywhere on the grid (not only the diagonal) and may be rectangular. The block-diagonal, square-tile special case is whatBlockTensorcaptures; the off-diagonal / rectangular cases (e.g. a non-totally-symmetric operator coupling different symmetry sectors) require this general form.ComputeGraph integration (Tier A)
This type satisfies
CoreBasicTensorConceptso it can be captured into a ComputeGraph for lifecycle orchestration (materialize / release / zero) and passed around as an operand handle. Because a multi-tile tensor has no single contiguous backing buffer,data()returnsnullptrfor the multi-tile case (and the single tile’s pointer in the degenerate one-cell grid), and the type advertises itself viais_tiled_tensor()so the graph can flag the handle (TensorHandle::is_tiled) and keep it out of dense buffer-level code paths. Tiled contraction inside the graph is intentionally not provided here.Added in version 2.0.0.
- dim(d: int) int#
Global extent along axis
d(sum of that axis’s tile sizes). Supports Python-style negative indexing.
- grid_size() int#
Number of grid cells (product of the per-axis tile counts). This is the number of possible tiles, not the number populated.
- add_tile(coord: list[int]) None#
Declare a tile at
coord. The declaration is deferred, with no storage allocated.Creates a shell
RuntimeTensorwith the right dims for that grid cell but no backing data. The tile is allocated later bymaterialize(or by the ComputeGraph MaterializationPass). No-op if the tile already exists.- Parameters:
coord – The grid coordinate, one index per axis.
- tile_view(coord: list[int]) RuntimeTensorView#
Python-facing tile accessor: materialize the tile at
coord(creating it if absent) and return a numpy-backed view of it. KEEP_ALIVE(0,1) ties this tensor’s lifetime to the returned view, so the tile’s storage outlives any numpy array Python builds from it.
- view(spaces: list[IndexSpace]) TiledRuntimeTensorView#
Create a non-owning
TiledRuntimeTensorViewrestricted to oneIndexSpaceper axis (e.g.A.view({o, v, o, v})). The view keeps this tensor alive; defined out-of-line below TiledRuntimeTensorView.
- class einsums.TiledRuntimeTensorC#
A runtime-rank, tile-wise sparse tensor.
This is the runtime-rank analogue of
TiledTensor. WhereTiledTensorcarries its rank as a compile-time template parameter (and therefore keys its tiles bystd::array<int, Rank>), TiledRuntimeTensor stores its rank at runtime and keys tiles bystd::vector<int>. Each populated tile is a denseRuntimeTensor(which reusesdetail::TensorImplfor its runtime-rank dims/strides machinery); absent tiles are rigorously zero and are not stored.Like
TiledTensorthis models a general tiled layout: a tile may sit anywhere on the grid (not only the diagonal) and may be rectangular. The block-diagonal, square-tile special case is whatBlockTensorcaptures; the off-diagonal / rectangular cases (e.g. a non-totally-symmetric operator coupling different symmetry sectors) require this general form.ComputeGraph integration (Tier A)
This type satisfies
CoreBasicTensorConceptso it can be captured into a ComputeGraph for lifecycle orchestration (materialize / release / zero) and passed around as an operand handle. Because a multi-tile tensor has no single contiguous backing buffer,data()returnsnullptrfor the multi-tile case (and the single tile’s pointer in the degenerate one-cell grid), and the type advertises itself viais_tiled_tensor()so the graph can flag the handle (TensorHandle::is_tiled) and keep it out of dense buffer-level code paths. Tiled contraction inside the graph is intentionally not provided here.Added in version 2.0.0.
- dim(d: int) int#
Global extent along axis
d(sum of that axis’s tile sizes). Supports Python-style negative indexing.
- grid_size() int#
Number of grid cells (product of the per-axis tile counts). This is the number of possible tiles, not the number populated.
- add_tile(coord: list[int]) None#
Declare a tile at
coord. The declaration is deferred, with no storage allocated.Creates a shell
RuntimeTensorwith the right dims for that grid cell but no backing data. The tile is allocated later bymaterialize(or by the ComputeGraph MaterializationPass). No-op if the tile already exists.- Parameters:
coord – The grid coordinate, one index per axis.
- tile_view(coord: list[int]) RuntimeTensorView#
Python-facing tile accessor: materialize the tile at
coord(creating it if absent) and return a numpy-backed view of it. KEEP_ALIVE(0,1) ties this tensor’s lifetime to the returned view, so the tile’s storage outlives any numpy array Python builds from it.
- view(spaces: list[IndexSpace]) TiledRuntimeTensorView#
Create a non-owning
TiledRuntimeTensorViewrestricted to oneIndexSpaceper axis (e.g.A.view({o, v, o, v})). The view keeps this tensor alive; defined out-of-line below TiledRuntimeTensorView.
- class einsums.TiledRuntimeTensorZ#
A runtime-rank, tile-wise sparse tensor.
This is the runtime-rank analogue of
TiledTensor. WhereTiledTensorcarries its rank as a compile-time template parameter (and therefore keys its tiles bystd::array<int, Rank>), TiledRuntimeTensor stores its rank at runtime and keys tiles bystd::vector<int>. Each populated tile is a denseRuntimeTensor(which reusesdetail::TensorImplfor its runtime-rank dims/strides machinery); absent tiles are rigorously zero and are not stored.Like
TiledTensorthis models a general tiled layout: a tile may sit anywhere on the grid (not only the diagonal) and may be rectangular. The block-diagonal, square-tile special case is whatBlockTensorcaptures; the off-diagonal / rectangular cases (e.g. a non-totally-symmetric operator coupling different symmetry sectors) require this general form.ComputeGraph integration (Tier A)
This type satisfies
CoreBasicTensorConceptso it can be captured into a ComputeGraph for lifecycle orchestration (materialize / release / zero) and passed around as an operand handle. Because a multi-tile tensor has no single contiguous backing buffer,data()returnsnullptrfor the multi-tile case (and the single tile’s pointer in the degenerate one-cell grid), and the type advertises itself viais_tiled_tensor()so the graph can flag the handle (TensorHandle::is_tiled) and keep it out of dense buffer-level code paths. Tiled contraction inside the graph is intentionally not provided here.Added in version 2.0.0.
- dim(d: int) int#
Global extent along axis
d(sum of that axis’s tile sizes). Supports Python-style negative indexing.
- grid_size() int#
Number of grid cells (product of the per-axis tile counts). This is the number of possible tiles, not the number populated.
- add_tile(coord: list[int]) None#
Declare a tile at
coord. The declaration is deferred, with no storage allocated.Creates a shell
RuntimeTensorwith the right dims for that grid cell but no backing data. The tile is allocated later bymaterialize(or by the ComputeGraph MaterializationPass). No-op if the tile already exists.- Parameters:
coord – The grid coordinate, one index per axis.
- tile_view(coord: list[int]) RuntimeTensorView#
Python-facing tile accessor: materialize the tile at
coord(creating it if absent) and return a numpy-backed view of it. KEEP_ALIVE(0,1) ties this tensor’s lifetime to the returned view, so the tile’s storage outlives any numpy array Python builds from it.
- view(spaces: list[IndexSpace]) TiledRuntimeTensorView#
Create a non-owning
TiledRuntimeTensorViewrestricted to oneIndexSpaceper axis (e.g.A.view({o, v, o, v})). The view keeps this tensor alive; defined out-of-line below TiledRuntimeTensorView.
- class einsums.TiledRuntimeTensorViewF#
A non-owning, per-irrep-sliced view of a
TiledRuntimeTensor.Produced by
TiledRuntimeTensor::viewwith oneIndexSpaceper axis. It does not own data: each populated tile is exposed as aRuntimeTensorViewsub-block of the parent tile (viaRuntimeTensor::at_view), so a view likeA[o, v, o, v]over an MO tensor selects the occ/vir sub-blocks of every symmetry-allowed tile with no copies. The parent must outlive the view.Added in version 2.0.0.
- has_tile(coord: list[int]) bool#
The view shares the parent’s sparsity pattern (same populated coords).
- class einsums.TiledRuntimeTensorViewD#
A non-owning, per-irrep-sliced view of a
TiledRuntimeTensor.Produced by
TiledRuntimeTensor::viewwith oneIndexSpaceper axis. It does not own data: each populated tile is exposed as aRuntimeTensorViewsub-block of the parent tile (viaRuntimeTensor::at_view), so a view likeA[o, v, o, v]over an MO tensor selects the occ/vir sub-blocks of every symmetry-allowed tile with no copies. The parent must outlive the view.Added in version 2.0.0.
- has_tile(coord: list[int]) bool#
The view shares the parent’s sparsity pattern (same populated coords).
- class einsums.TiledRuntimeTensorViewC#
A non-owning, per-irrep-sliced view of a
TiledRuntimeTensor.Produced by
TiledRuntimeTensor::viewwith oneIndexSpaceper axis. It does not own data: each populated tile is exposed as aRuntimeTensorViewsub-block of the parent tile (viaRuntimeTensor::at_view), so a view likeA[o, v, o, v]over an MO tensor selects the occ/vir sub-blocks of every symmetry-allowed tile with no copies. The parent must outlive the view.Added in version 2.0.0.
- has_tile(coord: list[int]) bool#
The view shares the parent’s sparsity pattern (same populated coords).
- class einsums.TiledRuntimeTensorViewZ#
A non-owning, per-irrep-sliced view of a
TiledRuntimeTensor.Produced by
TiledRuntimeTensor::viewwith oneIndexSpaceper axis. It does not own data: each populated tile is exposed as aRuntimeTensorViewsub-block of the parent tile (viaRuntimeTensor::at_view), so a view likeA[o, v, o, v]over an MO tensor selects the occ/vir sub-blocks of every symmetry-allowed tile with no copies. The parent must outlive the view.Added in version 2.0.0.
- has_tile(coord: list[int]) bool#
The view shares the parent’s sparsity pattern (same populated coords).
Functions#
- einsums.create_identity_tensor(name: str, dims: list[int]) Any#
Create a runtime-rank identity tensor from a runtime shape vector.
The runtime-rank form. The diagonal is as long as the shortest axis.
auto a = create_identity_tensor<double>("a", {3, 3}); // 3x3 identity auto b = create_identity_tensor<double>("b", {6, 3}); // ones at (0,0), (1,1), (2,2)Added in version 2.0.0.
- Parameters:
name – The name of the new tensor.
dims – The extent of each dimension.
- Returns:
A new tensor with ones along its diagonal and zeros elsewhere.
- einsums.create_random_definite(name: str, n: int) Any#
Python-bindable runtime-rank create_random_definite.
Builds a square SPD (or SND if mean < 0) matrix and returns it as a RuntimeTensor. Adapter over the typed Tensor<T, 2> entry point.
- einsums.create_random_semidefinite(name: str, n: int) Any#
Python-bindable runtime-rank create_random_semidefinite.
Builds a square positive (or negative) semi-definite matrix and returns it as a RuntimeTensor. Adapter over the typed Tensor<T, 2> entry point.
- einsums.create_random_tensor(name: str, dims: list[int]) Any#
Python-bindable runtime-rank create_random_tensor.
Takes
std::vector<size_t>for the bindings; forwards to the container overload.
- einsums.create_zero_tensor(name: str, dims: list[int]) Any#
Create a runtime-rank zero tensor from a runtime shape vector.
The runtime-rank form, exposed to Python as
create_zero_tensor.
- einsums.einsum(spec: str, C: Any, A: Any, B: Any, c_pf: Any = typename CType::ValueType{0}, ab_pf: Any = typename AType::ValueType{1}, conj_a: bool = False, conj_b: bool = False) None#
Graph-aware einsum: contract A and B according to
spec.specis a string of the form"<output> <- <a> ; <b>"; e.g."ij <- ik ; kj"(matrix multiply),"i <- ij ; j"(matrix- vector)," <- i ; i"(dot product).c_pfandab_pfdefault to 0 and 1, givingC = A op B, but can be set to accumulate (c_pf=1) or scale.Complex prefactors are fully supported for complex dtypes: the einsum node’s live params and its descriptor store PrefactorScalar (a variant covering float/double/complex<float>/complex<double>), so a complex
c_pf/ab_pfround-trips through capture and replay without narrowing.conj_a/conj_bconjugate A / B inside the contraction for complex dtypes, and are a no-op for real. They conjugate only the elements. A conjugate-transpose is the conj flag combined with transposed index placement in the spec, just like any transpose in einsum. To computeC = A^H @ B, store A as(k, i)so its row index k is the one contracted:// (A^H @ B)[i,j] = sum_k conj(A[k,i]) * B[k,j] einsum("ij <- ki ; kj", C, A, B, conj_a=True); // A^H @ B einsum("ij <- ik ; jk", C, A, B, conj_b=True); // A @ B^H einsum("ij <- ik ; kj", C, A, B, conj_a=True); // conj(A) @ B (no transpose)Equivalently, wrap an operand in
conj(...)directly in the spec; it ORs with the kwargs, soeinsum("ij <- conj(ki) ; kj", C, A, B)is also A^H @ B. Native for GEMM-shaped contractions via PackedGemm, with no operand copy. The generic loop conjugates per element otherwise. Not supported for tiled operands.
- einsums.is_running() bool#
Test whether the runtime system is currently running.
Whether the state is einsums::RuntimeState::Running.
Added in version 1.0.0.
- einsums.make_temp_path() str#
Generate a unique path in the system temporary directory.
The file is not created. For test scratch files that must not collide under parallel ctest.
- Returns:
A unique filesystem path. Converts to
pathlib.Pathin Python.
- einsums.permute(spec: str, C: Any, A: Any, c_pf: Any = typename CType::ValueType{0}, a_pf: Any = typename AType::ValueType{1}) None#
Graph-aware permute with explicit prefactors.
specis a permutation pattern such as"ji <- ij"(transpose) or"kji <- ijk"(rank-3 reorder). ComputesC = c_pf * C + a_pf * permute(A)according tospec.c_pfdefaults to 0 anda_pfto 1, i.e.C = permute(A).
- einsums.pool_empty(pool: MemoryPool, name: str, dims: list[int]) GeneralRuntimeTensor#
Python entry point for
pool_empty.Bound as
einsums.pool_empty(pool, name, dims, dtype)and reachable aspool.empty(...)after the Python layer attaches it to the class.Added in version 2.0.0.
- einsums.pool_reserve_cost(bytes: int) int#
The arena bytes a reservation of
bytesactually claims, headroom and rounding included. Planners budgeting against einsums:max-memory should charge this, not the raw sum.
- einsums.pool_zeros(pool: MemoryPool, name: str, dims: list[int]) GeneralRuntimeTensor#
Python entry point for
pool_zeros.Added in version 2.0.0.
- einsums.seed_random(seed: int) None#
Set the seed of the random number generator.
Seeds
random_engine, behindcreate_random_tensor,create_random_definiteand the randomized algorithms (truncated_svd,truncated_syev). Exposed so Python tests can reproduce draws made inside C++.Warning
The engine is process-global and unsynchronized. Seed during setup, not concurrently with threads that draw from it.
Added in version 1.0.0.
- Parameters:
seed – The new seed for the random number generator.
- einsums.set_log_level(level: int) None#
Set the runtime log level on the einsums logger.
Values mirror spdlog: 0=TRACE, 1=DEBUG, 2=INFO, 3=WARN, 4=ERROR, 5=CRITICAL, 6=OFF. Out-of-range values are clamped by spdlog. Compile-time disablement via
EINSUMS_ACTIVE_LOG_LEVELtakes precedence, so a runtimeset_log_level(0)cannot re-enable TRACE in a Release build.
Enumerations#
- class einsums.OptLevel#
Optimization level for Graph::optimize(), compiler-style.
O0: no passes; the graph runs exactly as captured.
O1: node-count cleanup only (constant folding, dead-scale removal, permute fusion, CSE, dead-node elimination, elementwise fusion) - cheap, no restructuring, no memory planning.
O2: the full default pipeline (cleanup + loop hoisting + cost-model chain restructuring + batching + reorder + distribution/GPU when available + in-place merging + free insertion + the memory arena).
- O0 = 0#
- O1 = 1#
- O2 = 2#
- class einsums.RuntimeState#
Holds the possible states for the runtime.
Added in version 1.0.0.
- Invalid = -1#
The state is invalid.
- Initialized = 0#
The runtime has been initialized.
- PreStartup = 1#
The runtime is running the pre-startup functions.
- Startup = 2#
The runtime is running the startup functions.
- PreMain = 3#
The runtime is preparing to run the main function.
- Starting = 4#
The runtime is starting the main function.
- Running = 5#
The main function is running.
- PreShutdown = 6#
The pre-shutdown functions are running.
- Shutdown = 7#
The shutdown functions are running.
- Stopping = 8#
The runtime is stopping.
- Terminating = 9#
The runtime is terminating.
- Stopped = 10#
The runtime has stopped.
- LastValidState = 10#
Indicates the last valid state. Anything past this is considered invalid.