TenfloweRS Core
The foundational crate of TenfloweRS, providing core tensor operations, device management, and the computational infrastructure for machine learning in Rust.
Stable (v0.2.0 -- 2026-07-13) | 1174 tests passing (26 skipped,
--all-features) | 0 clippy warnings
Overview
tenflowers-core implements:
- Multi-dimensional tensor operations with CPU and GPU support
- Device abstraction for heterogeneous computing (CPU, WGPU, CUDA, Metal, ROCm)
- Efficient memory management and zero-copy operations where possible
- Built on the SciRS2 numerical ecosystem (
scirs2-core,scirs2-linalg) - Operation registry with shape inference and kernel fusion
- Autocast, sparse tensors, fused ops, and advanced math functions
Features
- Device Management: Seamless CPU/GPU tensor operations with automatic device placement
- Data Types: Support for
f32,f64,i32,i64,u8, and more - Operations: Comprehensive set of tensor operations including:
- Arithmetic: element-wise and broadcasting operations
- Linear Algebra: matrix multiplication, decompositions, eigenvalues
- Neural Network: convolutions, pooling, activations
- Reductions: sum, mean, max, argmax along axes (including real
StdDev,L1Norm,L2Norm; segment reductions now support N-D data, not just 1-D) - Manipulation: reshape, transpose, concatenate, slice (strided slicing now uses correct row-major linear-index accumulation for every rank/shape combination, fixing a stride-direction bug that previously silently returned wrong elements for non-square, non-1D strided slices)
- Advanced Math: logsumexp, GELU, Mish, Swish, and more
- GPU Acceleration: WGPU-based compute shaders for cross-platform GPU support;
device::get_gpu_adapter_capabilitiesexposes a real, unprocessedwgpu::Adaptercapability snapshot (no vendor-specific guessing) - Operation Registry: Extensible dispatch registry with shape inference
- Kernel Fusion: Automatic fusion of eligible operation sequences
- Autocast: Automatic dtype promotion for mixed-precision workflows
- Sparse Tensors: COO and CSR sparse tensor support
- Fused Ops: Pre-fused compound operations for performance
- Automatic Fallback:
fallback::{get_fallback_config, set_fallback_config}for GPU-to-CPU operation recovery, backed by a thread-safeOnceLock<RwLock<FallbackConfig>>(replacing a priorunsafe static mutwhose writes raced unsynchronized against concurrent reads) - BLAS Integration: Optional acceleration via OxiBLAS
- LAPACK f64 Ops:
ops::lapack_f64— real LAPACK-backedinverse_f64,determinant_f64,svd_f64,solve_f64viascirs2-linalg - Graph Optimization:
session::SessionConfig::enable_graph_optimization(defaulttrue) wires constant folding, algebraic simplification, CSE, strength reduction, scheduling, and dead-code elimination into real session execution, with fetch-history-aware output protection across repeatedrun()calls with different fetch lists - ONNX Graph Interop:
onnx_interop::{convert, lowering, proto}— real protobuf import/export fortenflowers-core's own graph representation (OnnxModel/OnnxGraph/OnnxNode/OnnxTensorto_protobuf/from_protobuf), pluslowering::{OnnxOpMapping, StandardOpMapping, lower_graph}mapping parsed ONNX nodes (Add, Sub, Mul, Div, Relu, Sigmoid, Tanh, MatMul, Reshape, Transpose, Identity, Concat, Softmax, Flatten, Gemm) to real tenflowers-core ops;OnnxImporter/OnnxExporterfile/byte round-trips are real behind theonnxfeature (this is distinct fromtenflowers-neural's separateSequential-model ONNX subsystem) - Gradient Executor Bridge:
gradient_executormodule — aGradientExecutortrait (register_gradient_executor/get_gradient_executor) lettinggradient_validation_frameworkcall into a real forward+backward implementation supplied bytenflowers-autogradwithout a circular crate dependency; without a registered executor, validation now reports an honest "unverified" status instead of fabricatingpassed: true
Usage
Basic Tensor Operations
use ;
// Create tensors (from_vec / ones always start on Device::Cpu; use
// `.to_device(...)` below to move onto a GPU when the `gpu` feature is on)
let a = from_vec?;
let b: = ones;
// Arithmetic operations
let c = &a + &b; // Element-wise addition
let d = a.matmul?; // Matrix multiplication
// Reductions (axes, keepdims)
let sum = c.sum?; // Sum all elements
let mean = c.mean?; // Mean along axis 0
GPU Operations
Computation Graphs
Graph currently exposes a low-level node/edge builder rather than a fluent
expression API — there is no graph.matmul(...)/graph.add(...) sugar yet,
so graphs are assembled via add_node/add_edge and executed through a
Session built by create_session:
use HashMap;
use ;
use ;
// Build a computation graph: output = x + y
let mut graph = new;
let x_id = graph.add_node?;
let y_id = graph.add_node?;
let add_id = graph.add_node?;
graph.add_edge?;
graph.add_edge?;
// Execute with a session (feed dict and results are always Tensor<f32>)
let mut session = create_session;
let mut feed_dict = new;
feed_dict.insert;
feed_dict.insert;
let results = session.run?;
By default (SessionConfig::enable_graph_optimization == true), a session's
run() call applies constant folding, algebraic simplification,
common-subexpression elimination, strength reduction, scheduling, and
dead-code elimination before executing the graph; nodes fetched by any prior
run() call remain protected from later optimization passes even under a
different fetch list. NodeType::Variable nodes (stateful values such as
learned weights) are also supported, initialized either from an
AttributeValue::Tensor(...) under the "initializer" attribute key passed
to add_node, or with zeros by default.
Architecture
Core Components
| Item | Kind | Description |
|---|---|---|
Tensor<T> |
struct | Core N-dimensional array, generic over element type, wrapping CPU (ndarray) or GPU storage |
Device |
enum | Cpu / Gpu(usize) (feature gpu) / Rocm(usize) (feature rocm) placement target |
DType |
enum | Runtime dtype tag (Float32, Float64, Int32, ... Complex64) used by Graph, ONNX interop, and quantization |
TensorStorage<T> |
enum | Internal CPU (ArrayD<T>) vs. GPU-buffer storage backing a Tensor |
Graph |
struct | Low-level computation graph (add_node/add_edge/NodeType) |
Session / DefaultSession |
trait / struct | Graph execution (run, partial_run); build via create_session |
DispatchRegistry<T> |
struct | Extensible per-dtype operation dispatch with kernel selection |
ShapeInferenceRegistry |
struct | Automatic output-shape computation per operation |
fallback::{get_fallback_config, set_fallback_config} |
fn | Thread-safe global GPU-to-CPU fallback configuration |
gradient_executor::{GradientExecutor, register_gradient_executor} |
trait / fn | Bridge letting tenflowers-autograd supply real backward passes |
Integration with SciRS2
tenflowers-core is built directly on scirs2-core's ndarray-based array
type for CPU storage (there is no separate NumRS2 adapter crate/method —
Tensor interoperates with scirs2_core::ndarray directly):
use ;
use Tensor;
// Build a tensor from an existing scirs2-core/ndarray array
let array = from_shape_vec?;
let tensor = from_array;
// Read back a flat, contiguous view of the underlying data
if let Some = tensor.as_slice
Feature Flags
std(default): Standard library supportparallel(default): Parallel CPU operations via Rayongpu: Enable GPU support via WGPUcuda/nccl: gate the CUDA/NCCL module surface; Linux/Windows only, and no CUDA SDK is actually linked (cudarc/cuda-sysare not dependencies), so these operations return honestNotImplementederrors rather than real CUDA executioncudnn: gates the cuDNN module surface; nolibcudnn.sois linked, so all operations return honestNotImplementederrorsopencl: routes to thewgpubackend; present for API-surface completeness, no OpenCL SDK involvedmetal: Metal backend support (macOS)rocm: gates the ROCm/HIP module surface; nolibamdhip64.sois linked, so all operations return honestNotImplementederrorsblas/blas-openblas/blas-mkl/blas-accelerate: BLAS acceleration viandarray-linalgblas-oxiblas: Use OxiBLAS (oxiblas-ndarray) for accelerated linear algebra — the Pure-Rust BLAS optionsimd: reserved for future explicit SIMD opt-in; runtime-detected CPU SIMD (viastd::archintrinsics) is always active in thesimdmodule regardless of this flag — enabling it currently only gates optionaldispatch_registrySIMD kernel paths and benchmark helpersserialize: Enable serialization support via serdecompression: Enableoxiarc-archive-backed compressiononnx: Real protobuf-backed ONNX graph import/export (onnx_interop::{OnnxImporter, OnnxExporter})wasm: WebAssembly target support;wasm_optimization::tensorruntime-probesWebAssembly.validatefor SIMD support andtypeof SharedArrayBufferfor shared-memory support onwasm32targets (honestfalseoff-wasm32, not a hardcoded guess)autograd: reserved for future use; currently gates a single internal test only and does not affectgradient_executoror other production functionality (which work regardless of this flag)
Performance Considerations
- Tensors use reference counting for efficient memory management
- Operations are lazily evaluated when using computation graphs
- GPU operations are asynchronous and batched for efficiency
- Broadcasting follows NumPy semantics for compatibility
- Zero-copy views are used where possible (slicing, transposition)
- Kernel fusion reduces memory bandwidth pressure for eligible op sequences
Dependencies
Core dependencies:
scirs2-core/scirs2-linalg: numerical primitives (ndarray-based CPU storage, random, linear algebra), num-trait bounds, and parallel/SIMD utilities, re-exported throughout this crate rather than depending onndarray/num-traitsdirectlyrayon(optional, viaparallelfeature): parallel CPU operationswgpu(optional, viagpufeature): GPU compute supportbytemuck,half,num-complex: POD casting and half-precision/complex numeric typesoxifft: FFT (Pure-Rust, replacingrustfft)oxicode: serialization codec (Pure-Rust, replacingbincode)oxiblas-ndarray(optional, viablas-oxiblasfeature): Pure-Rust BLAS accelerationoxiarc-archive(optional, viacompressionfeature): compression (Pure-Rust, replacingzip/flate2/zstd)
License
Licensed under Apache-2.0