Guide B
The stack for backend developers
What happens below the tensor network algorithms: the ★ tenferro-rs tensor runtime with automatic differentiation, and underneath it small, tensor-free libraries for strided contraction, batched linear algebra, dense linear algebra and thread ownership that you can use on their own, from Rust or from C. If you maintain a first-principles, quantum chemistry or many-body code and need fast contractions without transposes, the middle of this page is for you.
tenferro-rs
A Rust-native tensor runtime with opt-in automatic differentiation: typed and dynamic dense tensors, einsum, linear algebra and FFT; eager AD with PyTorch-style backward() and traced AD with JAX-style VJP, JVP and Hessian vector products; CPU and CUDA, with an experimental XLA path. It is benchmarked against PyTorch and JAX, and every library below this point exists to make it fast.
Who owns what
The backend is split along one line: a host that knows about tensors, and providers that only see borrowed strided memory. Most design decisions follow from keeping that line clean.
| Layer | Owns | Leaves to others |
|---|---|---|
| ★ tenferro-rs (host) | tensor types, allocation, dtype dispatch, device placement, AD rules, graph tracing, gauge conventions, error wrapping; the engine that carries a thread pool, plans and buffers | the inner loops of contraction and factorization |
| cpueinsum | executing an N-ary einsum in a given order: which labels each intermediate keeps, one reusable scratch buffer | choosing the order, parsing "ij,jk->ik", GPUs |
| tcontract | one binary contraction over arbitrary strides: planning, packing, microkernels, threading inside the call | N-ary einsum, ordering, linear algebra, AD |
| tlinalg | batched factorizations and solves, the batch loop and its lane fan-out | tensors, allocation policy, dtype and device dispatch |
| strided-rs | the strided view types and traits everyone exchanges; permutation and elementwise kernels | everything above |
| threadteam | the CPU threads: the pool, the execution token handed down, and the cost model that sizes each parallel region | what runs on the threads |
| ★ colmat | dense and sparse matrix kernels: GEMM, factorizations, eigensolvers | batching, tensors |
Design principles
- Explicit execution, no ambient state. Threads come from one threadteam pool the caller builds, and scratch memory from a context the caller passes in. threadteam is the only place parallel tasks start; no library starts a global pool, and no environment variable changes results. Two consequences: the same call is reproducible regardless of what else runs in the process, and an outer scheduler (MPI, hataori, a Julia session) can partition the machine without fighting the libraries.
- Tensor-free provider interfaces. Providers take borrowed strided views plus a few scalars and flags. They can be tested and benchmarked on plain buffers, and a different host (a quantum chemistry code, another tensor library) can call them without adopting tenferro.
- Plan once, execute many times. Contractions and einsums have a plan object that fixes the strategy, kernel and blocking for given shapes and strides. Tensor network sweeps and iterative solvers repeat the same shapes thousands of times, so per-call overhead matters as much as peak throughput.
- Measured, not assumed. Performance claims live in benchmark repositories keyed by commit and hardware, with comparisons against PyTorch and JAX (for tenferro), TBLIS (for tcontract), vendor LAPACK (for tlinalg), and MKL and OpenBLAS (for colmat).
★ tenferro: the host
tenferro-rs is a Rust-native tensor runtime for scientific code: typed and dynamic dense tensors, einsum, linear algebra, FFT, and automatic differentiation, on CPU and CUDA (with explicit upload and download), with an experimental XLA path that lowers traced graphs to StableHLO and runs them on a PJRT plugin loaded at run time. tensor4all-rs uses it for every dense operation.
- Tensor types.
TypedTensor<T>and dynamicTensorfor direct compute;EagerTensoradds PyTorch-stylebackward();TracedTensorrecords a graph (in computegraph) for JAX-style VJP, JVP and composed higher-order derivatives such as Hessian vector products. - One engine. Every operation takes an explicit engine. A
CpuEnginebundles a threadteam pool with the plan cache and the buffer pool, so build it once and reuse it: a new engine per call throws its buffers away.CpuEngine::serial()needs no pool at all. - Conventions. Storage is column-major, matching LAPACK, Fortran and Julia. There is no facade crate: depend on
tenferro-runtime, a backend such astenferro-cpu, and the operation crates you use (tenferro-adfor traced AD). - Providers. On the CPU,
tenferro-einsumandtenferro-cpuexecute through cpueinsum (and so tcontract), andtenferro-linalgadapts tlinalg to an interface tenferro defines. The providers do not depend on tenferro.
A pooled engine and an operation on it, abridged from the tenferro examples and README:
use tenferro_cpu::{CpuEngine, Pool};
let mut engine = CpuEngine::new(Pool::builder().threads(4).build()?);
let product = a.matmul(&b, &mut engine)?;
The tenferro documentation has the quickstarts, tenferro-examples has runnable end-to-end examples (a physics-informed neural network, a neural ODE, a DeepONet and a neural-network quantum state) built against the released crates, and tenferro-benchmark compares it with PyTorch and JAX workload by workload.
cpueinsum: N-ary einsum in a given order
cpueinsum runs an einsum over integer labels with a contraction order supplied by the caller in SSA form. For each binary step it plans a tcontract call. On top it decides which labels every intermediate must keep (those in the output or needed later; everything else is summed as early as possible) and places all intermediates in one reusable scratch buffer.
It intentionally does not search for contraction orders and does not parse string notation. Those belong to the caller (tenferro, or your own code with an order from opt_einsum, cotengra or a hand-derived factorization).
d[i, l] = Σ a[i, j] b[j, k] c[k, l], contracting (a b) first. From the cpueinsum README:
use cpueinsum::strided_view::{StridedView, StridedViewMut};
use cpueinsum::{EinsumPlan, EinsumSpec, Exec, Layout, Scratch};
// Inputs are operands 0, 1, 2; step 0 makes operand 3.
let spec = EinsumSpec::new(&[&[0, 1], &[1, 2], &[2, 3]], &[0, 3], &[[0, 1], [3, 2]])?;
let cm = Layout::new(&[2, 2], &[1, 2])?;
let plan = EinsumPlan::<f64>::new(&spec, &[cm, cm, cm], cm)?;
let mut scratch = Scratch::new();
// ... build StridedViews over your buffers, then:
plan.execute_into(&mut Exec::serial(), &views, &mut out, &mut scratch)?;
Threading is explicit: build a threadteam::Pool once, wrap it with Pool::borrow(&pool), and mint Exec::new(&pool, budget)? for each call. For workloads made of many small heterogeneous contractions, BinaryPlan and GroupedPlan prepare jobs once and run a whole group under one scheduler.
tcontract: binary contraction without transposes
tcontract computes
D = alpha * op(A) * op(B) + beta * op(C)
for strided operands of f32, f64, c32 and c64, with contracted, batch and free indices, repeated indices (diagonals), reductions and conjugation. Operands are never transposed or copied into a canonical layout first. It was previously named tprims-rs and includes kernels contributed from Lukas Devos's tensorprimitives work.
How a contraction runs
- Describe the problem. A
Problemis built either from aDotGeneral(contracting and batch axes, as in XLA) or from index labels, together with the layouts (dims and strides) of A, B and D. - Plan once.
Plan<T>::newvalidates the problem and chooses a strategy and a kernel. The plan is reusable for every call with the same layouts. - Execute.
execute_intotakes an execution token (Exec::serial(), orExec::newon a threadteam pool the host owns) and the views.contract_batchedruns many independent problems of one shape.
| Strategy | Used when | How |
|---|---|---|
| packed | general strides and index orders | a TBLIS-style block-scatter driver packs strided operands straight into microkernel panels, with cache blocking |
| faer | the problem fuses into one batched GEMM without copies | calls colmat's matrix multiply directly on the views, in parallel only through a threadteam team |
| elementwise | every index is a batch index | a single elementwise pass |
Microkernel families cover scalar, AVX2, AVX-512 and NEON register tiles, native complex kernels, and portable reference kernels; the planner resolves the family for the target and freezes the blocking in the plan. tcontract-benchmark compares it with TBLIS shape by shape.
D = A B with column-major 2 × 2 operands. Abridged from crates/tcontract/examples/readme.rs, which CI compiles and runs:
use strided_view::{StridedView, StridedViewMut};
use tcontract::api::{DType, DotGeneral, LayoutSpec, OperandSpec, Problem};
use tcontract::{Plan, PlanConfig};
use tcontract_exec::Exec;
let layout = |dims: &[usize], strides: &[isize]| {
Ok(OperandSpec::new(LayoutSpec::new(dims, strides, 0)?))
};
// contract axis 1 of A with axis 0 of B; no batch axes
let dot = DotGeneral::new(&[1], &[0], &[], &[]);
let problem = Problem::from_dot_general(
DType::F64,
layout(&[2, 2], &[1, 2])?,
layout(&[2, 2], &[1, 2])?,
layout(&[2, 2], &[1, 2])?,
&dot,
)?;
let plan = Plan::<f64>::new(&problem, &PlanConfig::default())?;
println!("strategy: {:?}", plan.report().algorithm);
plan.execute_into(&mut Exec::serial(), 1.0, &av, &bv, &mut dv)?;
The C ABI
tcontract builds into one shared library, libtcontract_capi, that implements TAPP, the community standard C interface for tensor products, declared by the pinned upstream headers. A C or C++ program that includes only <tapp.h> can create tensor descriptors, plan and execute a contraction serially. On top of the standard, operands can be passed as DLPack tensors, and a few named extensions expose executors for multithreaded runs. Because the ABI is a standard, a code written against TAPP can switch between implementations without source changes.
tlinalg: batched linear algebra
tlinalg-rs holds the factorizations that tensor algorithms reduce to once a tensor is unfolded into matrices. It is the layer tenferro's CPU linear algebra has been extracted into.
The batched interface
Every entry point is batched in the style of PyTorch: one call takes a strided descriptor of rank 2 + B with dimensions [rows, cols, b...] and processes all B batch items. The library owns the loop over the batch, so it can decide whether to run many small matrices in parallel or give all threads to one large matrix. Outputs are compact and column-major. When items fail, the reported error is deterministic: the failing item with the lowest index.
| Family | Includes |
|---|---|
| SVD | thin, full, values only |
| QR | QR, column-pivoted QR (rank revealing), compact Householder form |
| LU and solves | packed LU, factor once and solve, full-pivot LU, triangular solve |
| Cholesky | factorization and solves |
| Eigensolvers | Hermitian (eigh, eigvalsh) and general (eig, eigvals) |
tlinalg is pure Rust, on colmat. It takes the same execution token as tcontract (tcontract_exec::Exec, built on threadteam); the library decides between fanning out over batch items (for small matrices) and letting colmat parallelize inside one item, and derives colmat's parallelism for each item from the token. tlinalg does not depend on tenferro: tenferro defines the interface it needs and adapts tlinalg to it.
strided-rs: the shared vocabulary
strided-rs defines StridedView, StridedViewMut and the raw descriptors that every CPU layer passes across crate boundaries, plus fast permutation and elementwise kernels. Arbitrary strides are allowed, including negative and zero (broadcast).
Because these types cross crate boundaries, every crate in a build must resolve to the same strided-rs release; two copies would produce two incompatible view types.
★ colmat: dense linear algebra
The pure Rust dense kernels come from colmat, tensor4all's library derived from faer by Sarah Quinones. It was published as the t4a-faer crates up to 0.33.0 and continues as colmat from 0.34.0, unchanged apart from the name. It provides dense and sparse linear algebra for scientific and HPC applications and is not API compatible with upstream: the caller owns a threadteam team and passes Par::Team for parallel work or Par::Seq for sequential work, and there is no implicit global thread pool. Its README lists why it can be trusted, each item one click from a file:
- Differential validation against LAPACK. Sixteen families of LAPACK 3.12's own test suites are ported and run nightly; a run is green only when nothing fails outside an explicit list of known failures.
- Allocation contracts are tested. A counting allocator proves that steady-state calls (SVD, eigensolvers, LQ and others) allocate nothing.
- Bitwise reproducibility across fresh threads, processes and repeated runs at a fixed thread count.
- Upstream defects are reported back. Every defect that also reproduces in published upstream crates is kept as a standalone reproducer in upstream-reports/ and linked from one upstream issue.
- Measured performance. colmat-benchmark compares it with upstream faer, MKL and OpenBLAS; in the published comparison on a Zen 5 host colmat is faster than both MKL and OpenBLAS in most of the measured cases.
Matrix multiply comes from t4a-gemm, a fork of gemm with Apple Silicon SME kernels. Migration guides cover Eigen, BLAS, LAPACK, Julia, NumPy and SciPy, nalgebra, ndarray and upstream faer users, with a table mapping LAPACK routines such as ?getrf and ?syevd to the call that replaces each. Every change is recorded in PATCHSET.md; colmat keeps upstream's license and attribution.
threadteam: one owner of CPU threads
threadteam is the only place in the stack where parallel tasks start. strided-rs, tcontract, cpueinsum, tlinalg, tenferro and colmat all take their threads from it.
Poolis built once by the caller, with a fixed number of threads.Execis the token a call receives: a budget of threads on a pool, which can be limited, reborrowed or split further down.Exec::serial()runs inline and never starts a thread.Teamhands a pool to colmat, which passes it on asPar::Team.- A cost model sizes each parallel region from the amount of work, so a small contraction does not wake every thread.
Today each pool runs on a private Rayon pool, but no Rayon type appears in any public signature, so the substrate can change without touching the libraries above.
Execution contexts and hataori
Each layer takes its own explicit context, and they all carry the same threadteam pool:
- tcontract, cpueinsum and tlinalg take an
Exectoken. - tenferro carries the pool inside its
CpuEngine, and tensor4all-rs wraps that in aCpuExecutionContext.
Above a single process, something has to split the machine. That is hataori: map and a dynamically scheduled pmap over serial, Rayon, MPI and hybrid execution, inspired by Distributed.jl. hataori splits the machine into ranks and thread domains and lends each task its share. MPI can be linked at build time or loaded at run time (through rsmpi-rt), so a Rust extension can share the MPI library of a Julia or Python host.
For first-principles, quantum chemistry and other host codes
Coupled cluster, integral transformations, density fitting, GW and many-body perturbation theory spend their time in contractions of tensors whose index order rarely matches what GEMM wants. The usual workaround (permute, call GEMM, permute back) costs memory traffic and extra buffers. tcontract is built to avoid exactly that, in the same spirit as TBLIS, and is designed to be called from code that has its own tensor containers.
- From C, C++ or Fortran: link
libtcontract_capiand program against the TAPP headers. Your arrays stay where they are; descriptors carry the strides. Fortran codes can call the C ABI throughiso_c_binding, and column-major layouts are first class. - From Python: DLPack operands let arrays exported by NumPy, PyTorch, JAX or CuPy style libraries be described without copying, given a thin binding layer.
- From Rust: depend on
tcontractdirectly for binary contractions, oncpueinsumif you already have a contraction order for a multi-tensor expression, and ontlinalgfor batched factorizations of the resulting matrices. None of them require tenferro. - Dense linear algebra:
colmatreplaces LAPACK calls one routine at a time; its LAPACK routine table says which call replaces?getrf,?gesvd,?syevdor?potrf. - Threads: pass your own threadteam pool. Nothing in these libraries competes with OpenMP or MPI in your code behind your back.
The essay Why rewrite first-principles codes in Rust discusses what this could mean for an existing DFT code.
If you are evaluating them for a production code, opening an issue with your typical tensor shapes is the most useful thing you can do: it feeds directly into the benchmark campaigns below.
Benchmarks
Every campaign keys its results by library commit and hardware profile and publishes a site.
| Repository | What it measures | Results |
|---|---|---|
| ★ tenferro-benchmark | tenferro against PyTorch and JAX on CPU and GPU, per workload class | site |
| ★ colmat-benchmark | colmat against upstream faer, MKL and OpenBLAS | site |
| tcontract-benchmark | binary contractions against TBLIS, per shape | site |
| tlinalg-benchmark | batched factorizations, tlinalg against vendor LAPACK | site |
| cpueinsum-benchmark | N-ary einsum over a standard corpus of einsum instances | site |
| ★ tensor4all-benchmark | tensor network level algorithms: QTT elementwise products, MPO MPO contraction | results |
The campaigns share campaign-toolkit for run manifests, timing protocol and result pages.
Contributing
All repositories accept issues and pull requests, including AI assisted contributions. The rules shared by every Rust repository are in the contribution rules; each repository adds its local facts in AGENTS.md and its contributing guide. Good first contributions are benchmark cases from real applications, kernels for hardware we have not tuned for, and bindings for other languages.