tensor4all

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.

★ Flagship

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.

The highlighted bands are the subject of this guide. Arrows from hataori show where execution resources enter the stack.

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.

LayerOwnsLeaves 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 buffersthe inner loops of contraction and factorization
cpueinsumexecuting an N-ary einsum in a given order: which labels each intermediate keeps, one reusable scratch bufferchoosing the order, parsing "ij,jk->ik", GPUs
tcontractone binary contraction over arbitrary strides: planning, packing, microkernels, threading inside the callN-ary einsum, ordering, linear algebra, AD
tlinalgbatched factorizations and solves, the batch loop and its lane fan-outtensors, allocation policy, dtype and device dispatch
strided-rsthe strided view types and traits everyone exchanges; permutation and elementwise kernelseverything above
threadteamthe CPU threads: the pool, the execution token handed down, and the cost model that sizes each parallel regionwhat runs on the threads
★ colmatdense and sparse matrix kernels: GEMM, factorizations, eigensolversbatching, tensors

Design principles

★ 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.

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

  1. Describe the problem. A Problem is built either from a DotGeneral (contracting and batch axes, as in XLA) or from index labels, together with the layouts (dims and strides) of A, B and D.
  2. Plan once. Plan<T>::new validates the problem and chooses a strategy and a kernel. The plan is reusable for every call with the same layouts.
  3. Execute. execute_into takes an execution token (Exec::serial(), or Exec::new on a threadteam pool the host owns) and the views. contract_batched runs many independent problems of one shape.
StrategyUsed whenHow
packedgeneral strides and index ordersa TBLIS-style block-scatter driver packs strided operands straight into microkernel panels, with cache blocking
faerthe problem fuses into one batched GEMM without copiescalls colmat's matrix multiply directly on the views, in parallel only through a threadteam team
elementwiseevery index is a batch indexa 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.

FamilyIncludes
SVDthin, full, values only
QRQR, column-pivoted QR (rank revealing), compact Householder form
LU and solvespacked LU, factor once and solve, full-pivot LU, triangular solve
Choleskyfactorization and solves
EigensolversHermitian (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:

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.

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:

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.

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.

RepositoryWhat it measuresResults
★ tenferro-benchmarktenferro against PyTorch and JAX on CPU and GPU, per workload classsite
★ colmat-benchmarkcolmat against upstream faer, MKL and OpenBLASsite
tcontract-benchmarkbinary contractions against TBLIS, per shapesite
tlinalg-benchmarkbatched factorizations, tlinalg against vendor LAPACKsite
cpueinsum-benchmarkN-ary einsum over a standard corpus of einsum instancessite
★ tensor4all-benchmarktensor network level algorithms: QTT elementwise products, MPO MPO contractionresults

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.