Tutorial: Computation Graphs#

The ComputeGraph module lets you capture a sequence of tensor operations into a graph, then execute and replay them. This is useful for iterative algorithms where the same operations run many times with changing data.

Inspired by CUDA Graphs and PyTorch FX, the Einsums compute graph also supports optimization passes, parallel execution, control flow, and profiler integration.

Capture is also what the optimizer works on. Every pass, every factorization and every schedule rewrite in the library reads a captured graph; eager execution gets none of them, and that is deliberate. Eager is the reference semantics this layer is validated against, so a numpy-style script stays eager and computes exactly what it wrote. Capture is how you ask for something else.

This page covers capturing, replaying and running the passes. For what the passes can do to the mathematics of a program, and for the annotations that let them, see Tutorial: The Algebraic Optimizer.

Setup#

#include <Einsums/ComputeGraph.hpp>
#include <Einsums/TensorUtilities/CreateRandomTensor.hpp>
#include <Einsums/TensorUtilities/CreateZeroTensor.hpp>

using namespace einsums;
namespace cg = einsums::compute_graph;

Basic Capture and Execute#

Wrap operations in a CaptureGuard to record them into a graph:

auto A = create_random_tensor<double>("A", 10, 5);
auto B = create_random_tensor<double>("B", 5, 8);
auto C = create_zero_tensor<double>("C", 10, 8);

cg::Graph graph("matmul");
{
    cg::CaptureGuard guard(graph);
    // Operations here are RECORDED, not executed
    cg::einsum("ij <- ik ; kj", &C, A, B);
}

// Execute the recorded operations
graph.execute();   // C = A * B

// Change A's data and replay
A.set_all(1.0);
graph.execute();   // C = A * B (with new A data)

Graph-Owned Tensors#

For intermediate tensors that shouldn’t outlive the graph, use create_tensor():

cg::Graph graph("pipeline");
auto &tmp = graph.create_zero_tensor<double, 2>("tmp", 10, 8);

{
    cg::CaptureGuard guard(graph);
    cg::einsum("ij <- ik ; kj", &tmp, A, B);
    cg::scale(2.0, &tmp);
    cg::axpy(1.0, tmp, &C);
}

graph.execute();
// tmp is destroyed when graph is destroyed

Available Operations#

All common tensor operations have graph-aware wrappers in the cg:: namespace:

  • Tensor algebra: einsum, permute, transpose, element_transform

  • BLAS: gemm, gemv, ger, dot, scale, axpy, axpby, direct_product

  • LAPACK: syev, gesv, invert

The returning forms of dot, norm, trace, syev, svd, qr, pow and det throw std::logic_error during capture, because they return new objects. dot, norm and syev have capturable pointer forms (cg::dot(&result, A, B), cg::syev(&A, &W)); svd, qr, pow and det have none and must run outside capture.

Optimization Passes#

The graph can be optimized before execution:

// Apply all default optimizations
auto pm = cg::PassManager::create_default();
graph.apply(pm);
graph.execute();

The default pipeline runs the passes below, in this order. The GPU and MPI passes join it only when the corresponding backend (or its mock) is built in, between StreamContractionFusion and InplaceOptimization. When a structural pass has changed the graph, the analysis passes run once more at the end so their annotations describe the final node set:

ProvenancePropagation

Carry a tag declared on a tensor down to the handles the passes below read, including a loop or setup body’s own handle for the same buffer.

TiledExpansion

Lower tiled operations into per-tile dense nodes so every pass below can read them. Whether a tiled contraction is densified and whether a tiled elementwise op is fused into one node are left to the cost model (Densify::Auto and FuseTiles::Auto).

SpacePropagation

Infer the index spaces of intermediates from their producers’ operands.

CrossSpaceValidation

Flag a contraction letter that binds slots of two different index spaces.

DeltaElimination

Rewrite a contraction against a tagged Kronecker delta as a rename, and a contraction over two spaces declared disjoint as a scaling.

AntisymmetryDetection

Establish, by reading the bound inputs, which of a permutation operator’s symmetries they actually have.

AntisymmetrizerLinearity

Pull a sum of antisymmetrized quantities inside one antisymmetrizer.

AntisymmetryInference

Tag the output of a permutation operator with the antisymmetry it always has.

AntisymmetrizerFolding

Collapse a permutation operator contracted against an antisymmetric operand into a scalar multiple.

AntisymmetrizerExpansion

Lower a remaining permutation operator into a contraction plus one permuted accumulation per term.

ConstantFolding

Pre-compute constant subexpressions.

ScaleAbsorption

Absorb scale into adjacent einsum prefactors.

PermuteFusion

Fold a pure axis reorder into the subscript of the einsum that reads it.

CSE

Common subexpression elimination.

DeadNodeElimination

Remove unused computations.

SymmetrizedAccumulation

Fold the r += s*(t + P(t)) symmetrization idiom.

ElementWiseFusion

Merge consecutive element-wise operations on one tensor.

LinearCombinationContractionFolding

Fold transpose-paired contractions over one operand into a single contraction.

DistributiveFactoring

Rewrite A*B1 + A*B2 as A*(B1 + B2).

LoopInvariantHoisting

Hoist invariant ops out of loops.

ScratchPrivatization

Rename reused scratch onto clones so false dependencies stop serializing the graph.

MultiTermFactorization

Re-bracket products and share partial products between them. The search half is off unless asked for; see Tutorial: The Algebraic Optimizer.

LayoutAssignment

Choose each intermediate’s storage order so that contraction kernels make fewer internal copies, and fold away a permuted copy the choice makes an identity.

ContractionPlanning

Cost-model-driven contraction ordering.

GEMMBatching

Batch independent GEMM calls into blas::gemm_batch.

Reorder

Minimize peak memory via node reordering.

IOPrefetch

Move DiskRead nodes early for I/O-compute overlap.

DistributionPlanning

Decide replicate vs. distribute per tensor.

Materialization

Insert allocation nodes for deferred tensors.

SymmetryPropagation

Tag intermediates whose symmetry is provable from their inputs.

ScalingAnalysis

Report every contraction’s cost polynomial and the rate-limiting term.

StreamContractionFusion

Fuse contractions that stream one large tensor into a single pass over it.

InplaceOptimization

Reuse buffers for in-place operations.

FreeInsertion

Release large intermediates after their last consumer.

MemoryPlanning

Analyze tensor lifetime intervals and pack non-overlapping intermediates into one shared arena.

See the pass catalog for what each one matches and what it reports.

No lossy pass is ever in this list. A factorization, a quadrature, a basis truncation or a memory cap is something a program asks for by name, so until it does, the answer this pipeline computes is the answer the program wrote. Tutorial: The Algebraic Optimizer covers what asking looks like.

You can also apply a single pass:

auto [modified, mem] = graph.apply<cg::passes::MemoryPlanning>();
mem.print_report(std::cout);

Index Space Annotation#

A tensor’s dimensions say how big this problem is. An index space says what an axis ranges over - occupied orbitals, virtuals, an auxiliary basis - which is what lets a pass reason about how a family of problems grows.

Spaces are registered once, with the letter each contributes to a cost polynomial and any relations that hold between them:

auto &registry = cg::global_space_registry();
auto  occ  = registry.register_space({.name = "occ",  .scale_symbol = "o"});
auto  virt = registry.register_space({.name = "virt", .scale_symbol = "v"});
registry.declare_less(occ, virt);        // there are fewer occupieds
registry.declare_disjoint(occ, virt);    // and no orbital is both

Tensors are then annotated one slot per axis, before the operations that use them are captured:

graph.annotate_spaces(T2, {occ, occ, virt, virt});

Only a program’s inputs need annotating. SpacePropagation carries the annotation through the intermediates, CrossSpaceValidation reports a letter that binds two different spaces, and ScalingAnalysis reports what the program costs as a polynomial in the scale symbols:

auto [modified, scaling] = graph.apply<cg::passes::ScalingAnalysis>();
scaling.print_report(std::cout);   // total flops: 2*o^2*v^4, and what limits it

From Python the same three passes run through PassManager, spaces are built with cg.index_space, and annotation takes names rather than ids:

import einsums.graph as cg

registry = cg.global_space_registry()
registry.register_space(cg.index_space("occ", "o"))
registry.register_space(cg.index_space("virt", "v"))

with cg.capture(g):
    cg.annotate(T2, ("occ", "occ", "virt", "virt"))
    ...

scaling = cg.ScalingAnalysis()
pm = cg.PassManager()
pm.add(scaling)
pm.run(g)
print(scaling.report_string())

Cost polynomials reach Python as their renderings - scaling.total_flops_str() and scaling.node_flops() - rather than as objects to compute with.

Annotating a program buys more than a report. A space carries a dim symbol, and an axis annotated with one is an axis a later bind may resize, which is what lets a saved graph be replayed on a different molecule; and a rewrite whose value depends on how the spaces compare is judged for the declared family rather than for the geometry the capture happened to hold. Tutorial: The Algebraic Optimizer covers both.

Pipeline: Multi-Stage Workflows#

For iterative algorithms with convergence checks:

cg::Pipeline pipeline("scf");

// Stage 1: Setup (runs once)
pipeline.add_stage("setup", [&]() {
    cg::einsum("ij <- ik ; kj", &F, H, D);
});

// Stage 2: Iteration loop (runs until convergence or max iterations)
pipeline.add_loop("iterate", 100,
    [&](size_t iter) { return std::abs(energy - energy_old) > 1e-8; },
    [&]() {
        cg::einsum("ij <- ik ; kj", &F, H, D);
        cg::syev(&F, &eigvals);   // F now holds the eigenvectors
        // ... update density, energy ...
    }
);

pipeline.execute();

Control Flow#

Conditionals and loops within a flat graph:

cg::Graph graph("adaptive");
{
    cg::CaptureGuard guard(graph);

    cg::scale(0.5, &value);

    graph.add_conditional("check",
        [&]() { return value(0) > threshold; },
        [&]() { cg::scale(0.1, &value); },   // then branch
        [&]() { cg::scale(10.0, &value); }    // else branch
    );
}

Profiling#

execute() automatically integrates with the Einsums profiler. Each node appears as a named region with timing data. Run with --einsums:profile:server and attach einsums profiler to see a real-time call tree and flame graph.

graph.execute();

// Print per-node timing
graph.print_timing_report(std::cout);

// Export graph as DOT for GraphViz
std::ofstream f("graph.dot");
graph.print_dot(f);

Rebinding Tensors#

Swap a tensor for a different one without re-capturing:

auto A1 = create_random_tensor<double>("A1", 5, 5);
auto A2 = create_random_tensor<double>("A2", 5, 5);

cg::Graph graph("rebind_demo");
{ /* capture with A1 */ }
graph.execute();  // Uses A1

graph.rebind(A1, A2);
graph.execute();  // Now uses A2 (same graph structure)

TaskPool Integration#

The TaskPool module provides fine-grained task parallelism that integrates directly with ComputeGraph.

Graph-capturable parallel_for#

cg::parallel_for() captures a data-parallel loop as a graph node. The graph’s topological sort ensures it runs before any node that reads its output tensors:

#include <Einsums/TaskPool/TaskPool.hpp>

cg::Graph graph("fock_build");
{
    cg::CaptureGuard guard(graph);

    // Node 1: parallel_for computes integrals (via TaskPool workers)
    cg::parallel_for("integrals", 0, n_pairs,
        [&](size_t pair) { compute_integrals(pair, J, K); },
        &J, &K);  // Declare J and K as outputs

    // Node 2: assemble F = H + 2*J - K (depends on J and K)
    cg::permute("ij <- ij", 0.0, &F, 1.0, H);
    cg::axpy(2.0, J, &F);
    cg::axpy(-1.0, K, &F);

    // Node 3: compute energy (depends on F)
    cg::parallel_reduce<double>("energy", 0, N, &energy,
        []() { return 0.0; },
        [&](size_t i, double &acc) {
            for (size_t j = 0; j < N; ++j)
                acc += D(i, j) * F(i, j);
        },
        [](double &g, double const &l) { g += l; },
        &D, &F);
}

// Execute: integrals -> assembly -> energy (automatic ordering)
graph.execute();

// Replay for next SCF iteration (same graph, different data)
J.zero(); K.zero(); F.zero();
graph.execute();

The tensor arguments at the end (&J, &K for parallel_for; &D, &F for parallel_reduce) declare tensor dependencies for the graph’s topological sort. Without them, the graph cannot know what the body lambda accesses.

DataflowExecutor#

For maximum overlap of independent graph nodes, use DataflowExecutor:

cg::DataflowExecutor df;
graph.execute(df);  // Independent nodes run concurrently via TaskPool

See the TaskPool documentation for full details on submit(), then(), when_all(), dataflow(), parallel_for(), and parallel_reduce().

GPU Offloading#

The ComputeGraph can automatically offload operations to the GPU. The user writes standard CPU code; the optimization passes handle placement, data transfers, and dispatch.

Note

GPU offload is a work in progress. The GPU passes run only on GPU-enabled (or mock) builds, and the transfer and execution backend they target is not yet complete.

Requirements#

  • On MPS, use float tensors (MPS only supports float32 GEMM; double stays on CPU). CUDA also takes double.

  • The operation must be expensive enough to beat transfer and launch overhead under GPUPlacement’s cost model. A node with no flop estimate falls back to a size threshold (default 64 KB of memory traffic).

  • Use PassManager::create_default() to include GPU passes

// Write normal code with float tensors
auto A = create_random_tensor<float>("A", 256, 256);
auto B = create_random_tensor<float>("B", 256, 256);
auto C = create_zero_tensor<float>("C", 256, 256);

cg::Graph graph("my_computation");
{
    cg::CaptureGuard guard(graph);
    cg::einsum("ij <- ik ; kj", 0.0, &C, 1.0, A, B);
}

// Apply all passes including GPU optimization
auto pm = cg::PassManager::create_default();
graph.apply(pm);

// Execute --- nodes GPUPlacement chose run on the GPU
graph.execute();

The default pass manager includes these GPU-related passes:

  1. GPUPlacement decides which nodes run on GPU based on a cost model comparing estimated CPU time against GPU time plus transfer overhead.

  2. TransferInsertion adds HostToDevice / DeviceToHost nodes around GPU operations. It skips H2D for dead inputs, such as C in C = A*B when c_prefactor == 0, and inserts a final D2H for user-visible tensors left on device so the graph is self-contained.

  3. TransferElimination removes redundant transfers when consecutive GPU nodes share a tensor. It uses Belady’s optimal eviction under memory pressure.

  4. GPUDiagnostics logs GPU vs. CPU node counts, transfer bytes, and peak device memory.

  5. StreamAssignment tags transfer nodes with stream IDs for future async overlap.

GPU Pass Control#

Disable GPU offloading at runtime:

./my_program --einsums:gpu:disable

Disable a specific pass:

./my_program --einsums:pass:disable=GPUPlacement

Or build a custom pass manager without GPU passes:

cg::PassManager pm;
pm.add<cg::passes::ConstantFolding>();
pm.add<cg::passes::ScaleAbsorption>();
pm.add<cg::passes::CSE>();
// No GPU passes
graph.apply(pm);

Tuning the Cost Model#

The GPUPlacement pass uses a cost model to decide if an operation is worth offloading. You can tune the parameters:

cg::passes::GPUPlacement placement;
placement.cpu_throughput_gflops = 50.0;    // Your CPU's peak GFLOP/s
placement.gpu_throughput_gflops = 5000.0;  // Your GPU's peak GFLOP/s
placement.pcie_bandwidth_gbs   = 12.0;     // PCIe bandwidth (0 for unified memory)
placement.gpu_launch_overhead_us = 10.0;   // Kernel launch latency

cg::PassManager pm;
pm.add(std::make_shared<cg::passes::GPUPlacement>(std::move(placement)));
// ... add other passes ...

Interaction with ConstantFolding#

The ConstantFolding pass pre-computes, on CPU at optimization time, any node whose inputs are all graph-owned intermediates (create_tensor()) that no node in the graph writes. Such a node is replaced with a no-op before GPUPlacement runs, so it never reaches the GPU.

User-owned tensors are never treated as constant, since they may change between graph.execute() calls, so a graph fed from user tensors, like the example above, folds nothing.

If you want to force GPU execution of a folded node for benchmarking or demonstration, build a custom PassManager that skips ConstantFolding:

cg::PassManager pm;
// Skip ConstantFolding so the GPU handles the computation
pm.add<cg::passes::ScaleAbsorption>();
pm.add<cg::passes::CSE>();
pm.add<cg::passes::DeadNodeElimination>();
pm.add<cg::passes::GPUPlacement>();
pm.add<cg::passes::TransferInsertion>();
pm.add<cg::passes::TransferElimination>();
pm.add<cg::passes::GPUDiagnostics>();
graph.apply(pm);

Unified Memory (Apple Silicon)#

On Apple Silicon, the CPU and GPU share physical memory. The ComputeGraph detects this via gpu::has_unified_memory and skips the actual H2D/D2H memcpy calls at execution time. The GPU reads tensor data directly from host memory through zero-copy MTLBuffer wrappers.

The transfer nodes still exist in the graph structure, but their execution is a no-op on unified memory. This means the graph is portable across backends without code changes.

Graph Visualization#

After applying GPU passes, print_dot() colors nodes by execution target:

  • Blue nodes run on GPU.

  • Orange nodes are H2D/D2H transfers.

  • White nodes run on CPU.

graph.print_dot(std::cout);  // Pipe to: dot -Tpng > graph.png

The JSON output (graph.to_json()) includes "target": "GPU" and "stream_id" fields for each node.

Custom Operations and Disk I/O#

Not every operation has a built-in graph wrapper. Use cg::custom() for user-defined computations like integral evaluation, and cg::read() / cg::write() for disk I/O:

cg::Graph graph("scf_iteration");
auto &CF = graph.create_zero_tensor<double, 2>("CF", nmo, nmo);
{
    cg::CaptureGuard guard(graph);

    // Load integrals from disk
    cg::read("load ERI", "integrals.h5", "/eri", &ERI, [&]() {
        h5file.read("/eri", ERI);
    });

    // Custom computation: build Fock matrix
    cg::custom("build_fock",
        std::tie(ERI, D),    // inputs
        std::tie(F),         // outputs
        [&]() { build_fock_matrix(ERI, D, F); });

    // Standard einsums: F_mo = C F C, one pairwise contraction at a time
    cg::einsum("pj <- pi ; ij", 0.0, &CF, 1.0, C, F);
    cg::einsum("pq <- pj ; jq", 0.0, &F_mo, 1.0, CF, C);

    // Checkpoint to disk
    cg::write("save F_mo", "checkpoint.h5", "/fock_mo", &F_mo, [&]() {
        h5file.write("/fock_mo", F_mo);
    });
}

The graph tracks dependencies automatically: build_fock waits for load ERI, the einsum waits for build_fock, and the checkpoint waits for the einsum. GPU passes will keep DiskRead/DiskWrite on CPU and insert appropriate transfers around GPU-placed operations.

The graph cannot see inside a cg::custom closure, so it assumes the closure may read state the graph does not track, such as a counter captured by reference, or act outside the tensors it lists, such as printing or writing a file. Such a node is never hoisted out of a loop, never removed because nothing reads its outputs, and keeps its place relative to other custom nodes, parameter writes, and disk reads and writes. When the closure reads only the tensors it lists and does nothing but write the tensors it lists, say so with cg::pure, and the optimizer treats it like a built-in operation:

cg::custom(cg::pure, "build_fock", std::tie(ERI, D), std::tie(F),
    [&]() { build_fock_matrix(ERI, D, F); });

From Python, pass pure=True to cg.custom.

Async I/O: Overlapping Reads with Compute#

For I/O-bound workflows, use cg::read_async() / cg::write_async() to overlap disk I/O with independent computation. These accept three lambdas: start_fn (begins I/O), finish_fn (waits for completion), and sync_fn (synchronous fallback).

std::future<void> io_future;

cg::Graph graph("prefetch_pipeline");
{
    cg::CaptureGuard guard(graph);

    // Async read: start kicks off background I/O
    cg::read_async("load ERI", "integrals.h5", "/eri", &ERI,
        /*start*/  [&]() { io_future = std::async(std::launch::async,
                       [&]{ h5file.read("/eri", ERI); }); },
        /*finish*/ [&]() { io_future.get(); },
        /*sync*/   [&]() { h5file.read("/eri", ERI); }
    );

    // Independent computation, runs concurrently with the read
    cg::einsum("ij <- ik ; kj", 0.0, &C, 1.0, A, B);

    // Depends on ERI, waits for async read to finish
    cg::custom("build_fock", std::tie(ERI, D), std::tie(F),
        [&]() { build_fock_matrix(ERI, D, F); });
}

// IOPrefetch moves DiskRead to position 0, maximizing overlap window
auto pm = cg::PassManager::create_default();
graph.apply(pm);

// DataflowExecutor enables the overlap
cg::DataflowExecutor df;
graph.execute(df);

How it works#

  1. IOPrefetch pass moves the DiskRead to the beginning of the schedule

  2. DataflowExecutor calls async_start immediately

  3. While I/O runs in the background, the executor runs independent compute (A*B)

  4. Right after async_start, the executor queues async_finish as a task of its own, which blocks until the read completes

  5. build_fock runs with the loaded data once that task has finished

SequentialExecutor and OpenMPExecutor call the sync_fn fallback so that no overlap occurs. Use DataflowExecutor for async I/O overlap.

See examples/AsyncIO.cpp for a complete working example.

Profiler Session Save#

Save the complete profiling session (call tree, timing, annotations, and ComputeGraph structure) to a JSON file for offline analysis:

./my_program --einsums:profile:save=session.json

The file is written as the program exits, with or without --einsums:profile:server. einsums profiler --load opens it. Multiple runs append to the same file, creating a multi-session comparison:

# Run multiple times; sessions accumulate
./program --einsums:profile:save=runs.json
./program --einsums:profile:save=runs.json

# Load all in the viewer
einsums profiler --load runs.json

The saved JSON includes:

  • Aggregated profiling data (call tree, exclusive/inclusive times, annotations)

  • ComputeGraph node structure (kind, target, stream, inputs/outputs, timing)

  • Tensor metadata (name, dimensions, dtype)

  • Graph edges (data flow between operations)

Runtime Lifecycle#

The Einsums runtime automatically calls finalize() when einsums::start() returns. The shutdown sequence is:

  1. The pre-shutdown functions.

  2. The shutdown functions, which include each module’s cleanup and any user-registered shutdown hooks.

  3. Profiler finalize, which writes the --einsums:profile:save session file, if one was asked for, and the text report if enabled.

  4. Teardown of the runtime’s global state.

No explicit finalize() call is needed. The Runtime destructor handles everything when the unique_ptr<Runtime> goes out of scope. Calling finalize() explicitly is safe but redundant.

Workspace and Deferred Allocation#

For distributed-ready code, use declare_tensor() instead of create_*_tensor(). Tensors are declared with their shape but no data is allocated until the Materialization pass runs during apply(pm). This enables the DistributionPlanning pass to decide tensor placement before allocation:

cg::Workspace ws("calculation");

// No data allocated, just shape + metadata
auto &eri = ws.declare_tensor<double, 4>("ERI", nao, nao, nao, nao);
auto &C   = ws.declare_zero_tensor<double, 2>("C", nao, nmo);

cg::Pipeline scf("scf");
scf.set_workspace(ws);

auto &F = scf.declare_zero_tensor<double, 2>("F", nao, nao);

{
    auto &stage = scf.add_stage("compute");
    cg::CaptureGuard guard(stage);
    cg::einsum("ij <- ijkl ; kl", 0.0, &F, 1.0, eri, D);
}

auto pm = cg::PassManager::create_default();
scf.apply(pm);   // Distribution + Materialization happens here
scf.execute();    // Tensors allocated just-in-time

Three scoping levels:

  • Workspace holds tensors shared across Pipelines, such as the ERI and MO coefficients.

  • Pipeline holds tensors shared across stages, such as the Fock and density matrices.

  • Graph holds single-computation intermediates.

See Workspace and deferred allocation for full details.

Distributed Computing#

When EINSUMS_WITH_MPI=ON, the Comm module provides MPI-based distributed computing. The user writes einsum(C, A, B) unchanged; the ComputeGraph passes handle distribution and communication:

auto pm = cg::PassManager::create_default();
scf.apply(pm);
// DistributionPlanning: eri (100GB) → block-distributed across ranks
//                       F, C (small) → replicated
// Materialization: each rank allocates its local eri slice + full F, C
// CommunicationInsertion: allreduce after eri contraction

scf.execute();
// Each rank computes its portion. Communication handled automatically.

Without MPI, the mock backend runs everything on a single rank, meaning the same code works in both serial and distributed modes.

See Distributed computing for full details.

Hardware-Aware Optimization#

The ContractionPlanning pass uses a CostModel to make architecture-specific decisions. Without a measured profile it comes from a database of 25+ pre-filled profiles for common CPUs and GPUs, auto-detected at runtime:

// Automatic detection (runs inside create_default()):
auto profile = CostModel::detect_default();
// → "Apple M4 Pro" on your machine

Measure the machine once for precise numbers. Every later program on it finds the profile einsums tune writes, with no flag:

einsums tune

See Hardware profiles for full details.

What’s Next#

  • Tutorial: The Algebraic Optimizer – Annotations, tags, providers, and the rewrites that change what a program computes

  • Tutorial: Performance Tuning – Understanding dispatch and profiler usage

  • GPUOffload.cpp in the ComputeGraph examples — full GPU offloading demo

  • SCFSimulation.cpp — iterative SCF with custom operations and loops

  • AsyncIO.cpp — async I/O overlap with DataflowExecutor

  • The examples/ directory in the ComputeGraph module contains full, compilable examples for each feature.