tenrso-ad
Production-Grade Automatic Differentiation for TenRSo
Advanced automatic differentiation with custom VJP rules, decomposition gradients, gradient checkpointing, Hessian computation, sparse gradient support, and mixed precision training.
Overview
tenrso-ad provides state-of-the-art gradient computation for tensor operations in the TenRSo ecosystem:
- Custom VJP rules - Vector-Jacobian Products for tensor contractions, avoiding AD tape blow-up
- Decomposition gradients - Backpropagation through CP, Tucker, and TT decompositions
- Gradient checkpointing - Trade computation for memory (O(n) -> O(sqrt(n)))
- Higher-order derivatives - Hessian-vector products and Newton's method
- Sparse gradients - Up to 98% memory savings for sparse gradients
- Mixed precision - FP16/BF16 with automatic loss scaling
- Graph-based AD - PyTorch-style dynamic computation graphs
- Gradient monitoring - Vanishing/exploding gradient detection
- Optimizers & LR schedulers - SGD, Adam, AdamW, RMSprop, AdaGrad
- Parallel execution - Multi-threaded gradient computation with configurable thread pools
- Integration hooks - Connect to external AD frameworks
Features
Core AD Capabilities
- Einsum VJP: Automatic adjoint generation for generalized tensor contractions
- Special handling for scalar outputs (inner products, norms)
- Automatic adjoint spec generation for complex contractions
- Zero tape overhead for backward pass
- Element-wise VJP: Gradients for unary/binary operations with custom derivatives
- Reduction VJP: Sum, mean, max, min with correct broadcasting
- CP-ALS gradients: Factor matrix and weight gradients via MTTKRP
- Tucker-HOOI gradients: Core and factor matrix gradients via mode-n products
- TT-SVD gradients: Efficient gradients through Tensor Train cores
Gradient Checkpointing
Memory-efficient training via selective recomputation:
- Configurable strategies: Uniform, MemoryAware, All, None
- Reduces memory from O(n) to O(sqrt(n)) for deep networks
- Example: 50-layer network saves 60-90% memory
Higher-Order Derivatives
Hessian computation and second-order optimization:
- Hessian-vector products in O(n) time (no full Hessian materialization)
- Diagonal Hessian for preconditioning
- Support for Newton's method (10x faster convergence)
Sparse Gradients
Efficient handling of highly sparse gradients:
- COO format sparse representation
- Automatic dense/sparse format selection
- Memory savings up to 98% for 99% sparse gradients
- Gradient compression to target sparsity
Mixed Precision Training
- FP16 and BF16 gradient computation
- Automatic loss scaling to prevent underflow
- Configurable scale factor growth and decay
Graph-Based AD (PyTorch-style)
- Dynamic computation graphs
- Graph optimization passes: operation fusion, dead code elimination, memory planning
- Eager execution with gradient accumulation
Gradient Monitoring
- Vanishing gradient detection (configurable thresholds)
- Exploding gradient detection
- Gradient health statistics and reporting
Optimizers & LR Schedulers
Optimizers: SGD (with momentum), Adam, AdamW, RMSprop, AdaGrad Schedulers: StepLR, ExponentialLR, CosineAnnealing, ReduceLROnPlateau
Installation
[]
= "0.1.0-rc.1"
Quick Start
Basic Einsum Gradients
use ;
use DenseND;
use execute_dense_contraction;
use EinsumSpec;
// Forward: C = A @ B
let spec = parse?;
let a = from_vec?;
let b = from_vec?;
let c = execute_dense_contraction?;
// Backward: compute dL/dA and dL/dB
let grad_c = ones;
let vjp = new;
let grads = vjp.vjp?;
Gradient Checkpointing
use ;
use Arc;
let config = CheckpointConfig ;
let mut sequence = new;
sequence.add_operation;
// Forward pass stores only checkpoints — O(sqrt(n)) memory
let output = sequence.forward?;
// Backward pass recomputes intermediate values
let grad = sequence.backward?;
Hessian Computation
use ;
// Hessian-vector product H*v in O(n) time
let hv = hessian_vector_product?;
// Diagonal of Hessian for preconditioning
let diag = compute_hessian_diagonal?;
// Newton's method optimization
for _ in 0..iterations
Sparse Gradients
use ;
let config = SparsityConfig ;
let grad = from_dense_auto?;
// Dense: 1M parameters x 8 bytes = 7.63 MB
// Sparse (99% zeros): 10K nonzeros x 16 bytes = 0.15 MB
// Savings: 98%
// Gradient compression to target sparsity
grad.compress?; // Keep only top 10% values
CP Decomposition Gradients
use cp_reconstruction_grad;
let factors = vec!;
let weights = Some;
let grad_output = ones;
let =
cp_reconstruction_grad?;
Parallel Gradients
use ;
let config = ParallelConfig ;
let grad = parallel_elementwise_vjp?;
Graph-Based AD
use ;
let mut graph = new;
let x = graph.variable?;
let y = graph.matmul?;
let loss = graph.reduce_sum?;
graph.backward?;
let grad_x = graph.gradient?;
Examples
Comprehensive examples demonstrating all features:
Basic Examples
basic_einsum_ad.rs- Matrix multiplication, inner product, outer productcp_decomposition_gradients.rs- CP gradients with/without weightscustom_ad_operations.rs- Custom operations with GenericAdAdapter
Advanced Examples
gradient_checkpointing.rs- Memory-efficient training (4 practical examples)hessian_optimization.rs- Newton's method vs gradient descentsparse_gradients.rs- Large-scale sparse gradient handlingmixed_precision_training.rs- FP16/BF16 with automatic loss scalinggradient_monitoring.rs- Vanishing/exploding gradient detectionoptimizers_showcase.rs- Complete optimizer and scheduler demonstrationsgraph_based_ad.rs- PyTorch-style dynamic computation graphs
Testing
Comprehensive test suite with 100% pass rate (154/154 tests):
- Unit tests (134): Core VJP, gradient, checkpointing, Hessian, sparse, mixed precision, monitoring, optimizers, graph, graph optimizer, storage, utilities
- Integration tests (10): End-to-end workflows including edge cases
- Property tests (10): Mathematical properties via proptest
Test Breakdown
graph.rs: 15 tests (computation graph, dynamic AD)graph_optimizer.rs: 12 tests (operation fusion, DCE, memory planning)monitoring.rs: 15 tests (gradient health tracking)mixed_precision.rs: 14 tests (FP16/BF16 training)sparse_grad.rs: 13 tests (sparse gradient handling)optimizers.rs: 13 tests (SGD, Adam, AdamW, RMSprop, AdaGrad, LR schedulers)checkpoint.rs: 10 tests (memory-efficient backward pass)hessian.rs: 9 tests (second-order derivatives)utils.rs: 8 tests (gradient utilities)storage.rs: 7 tests (memory optimization)vjp.rs: 5 tests (VJP rules + scalar output handling)parallel.rs: 5 tests (parallel computation)grad.rs: 4 tests (decomposition gradients)hooks.rs: 4 tests (external AD integration)gradcheck.rs: 3 tests (gradient verification)
Performance
Benchmarks
15 comprehensive benchmarks available via cargo bench:
Gradient Benchmarks (gradient_benchmarks):
| Benchmark | Operation | Size Range | Purpose |
|---|---|---|---|
einsum_vjp_matmul |
Matrix multiplication | 16-256 | Core contraction gradients |
einsum_vjp_tensor_contraction |
Tensor operations | 8-64 | Higher-order tensors |
elementwise_vjp |
Element-wise ops | 1K-1M | Parallel scaling |
reduction_vjp |
Reductions | 100-2K | Broadcasting correctness |
cp_reconstruction_grad |
CP gradients | rank 8-64 | Decomposition performance |
tucker_reconstruction_grad |
Tucker gradients | core 4-16 | Multi-mode products |
gradcheck |
Finite differences | 10-30 | Verification overhead |
Graph Benchmarks (graph_benchmarks):
| Benchmark | Operation | Size Range | Purpose |
|---|---|---|---|
graph_arithmetic |
Basic ops | 100-10K elements | Arithmetic operation overhead |
graph_neural_layer |
Neural layer | batch 1-64 | Forward + backward performance |
graph_deep_network |
Deep network | 5-20 layers | Multi-layer scalability |
graph_construction |
Graph building | 10-200 ops | Construction overhead |
graph_backward_only |
Backward pass | various | Isolated backward perf |
graph_activations |
Activations | various | ReLU, Sigmoid, Tanh |
graph_optimization |
Optimization | various | Fusion, DCE impact |
graph_memory |
Gradient storage | 10-100 vars | Memory usage patterns |
Memory Savings
| Feature | Scenario | Memory Reduction |
|---|---|---|
| Checkpointing | 50-layer network | 60-90% |
| Sparse gradients | 99% sparsity | 98% |
| Smart storage | Large tensors | Zero-copy sharing |
Speedups
| Feature | Workload | Speedup |
|---|---|---|
| Parallel VJP | 1M elements, 8 cores | 3-4x |
| Parallel accumulation | Multiple gradients | 5-8x |
| Hessian diagonal | vs full Hessian | 100-1000x |
| Newton's method | vs gradient descent | 10x fewer iterations |
Architecture
tenrso-ad/
├── vjp.rs # VJP rules (einsum, element-wise, reductions)
├── grad.rs # Decomposition gradients (CP, Tucker, TT)
├── graph.rs # Graph-based AD (PyTorch-style)
├── graph_optimizer.rs # Graph optimization passes
├── checkpoint.rs # Gradient checkpointing
├── hessian.rs # Higher-order derivatives
├── sparse_grad.rs # Sparse gradient support
├── mixed_precision.rs # Mixed precision training
├── monitoring.rs # Gradient health monitoring
├── optimizers.rs # Optimizers and LR schedulers
├── gradcheck.rs # Finite difference verification
├── hooks.rs # External AD framework integration
├── parallel.rs # Parallel gradient computation
├── storage.rs # Memory-optimized tensor storage
└── utils.rs # Gradient manipulation utilities
SciRS2 Policy
100% compliant - All operations use scirs2-core for scientific computing:
// REQUIRED
use Array;
use thread_rng;
use Float;
// FORBIDDEN
use Array; // Never import directly
use thread_rng; // Never import directly
Dependencies
- tenrso-core - Dense tensor representation
- tenrso-exec - Execution of contractions
- tenrso-decomp - CP/Tucker/TT algorithms
- tenrso-planner - Contraction planning
- scirs2-core - Scientific computing primitives
- scirs2-linalg - Linear algebra operations
- rayon - Parallel execution
License
Apache-2.0 or MIT (dual licensed)
Related Projects
tenrso-core- Core tensor data structurestenrso-exec- Execution enginetenrso-decomp- Decomposition algorithmstenrso- Main TenRSo library
Status: Alpha (production-ready internals) | Version: 0.1.0-rc.1 | Tests: 154/154 passing