ad_trait

Library Listed

Easy to use, efficient, and highly flexible automatic differentiation in Rust

Checked · Sources

Downloads
2,070
Dependents
2
Stars
24
Forks
9
Contributors
2
Commits
96
Latest release
0.3.1 ·

About

From the project README ·

Introduction

This crate brings easy to use, efficient, and highly flexible automatic differentiation to the Rust programming language. Utilizing Rust's extensive and expressive trait features, the several types in this crate that implement the trait AD can be thought of as a drop-in replacement for an f64 or f32 that affords forward mode or backwards mode automatic differentiation on any downstream computation in Rust.

Read the full README

Key Features

  • ad_trait supports reverse mode or forward mode automatic differentiation. The forward mode automatic differentiation implementation can also take advantage of SIMD to compute multiple tangents simultaneously.
  • Second-Order AD: Supports computing Hessians via recursive dual types, including Forward-over-Forward and Forward-over-Reverse modes.
  • The core rust f64 or f32 types also implement the AD trait, meaning any functions that take an AD trait object as a generic type can handle either standard floating point computation or derivative tracking automatic differentiation with essentially no overhead.
  • The provided types that implement the AD trait also implement several useful traits that allow it to operate almost exactly as a standard f64. For example, it even implements the RealField and ComplexField traits, meaning it can be used in any nalgebra or ndarray computations.

Example

use ad_trait::AD;
use ad_trait::function_engine::FunctionEngine;
use ad_trait::differentiable_function::{DifferentiableFunctionTrait, FiniteDifferencing, ForwardAD, ForwardADMulti, ReverseAD};
use ad_trait::forward_ad::adfn::adfn;
use ad_trait::reverse_ad::adr::adr;

#[derive(Clone)]
pub struct Test<T: AD> {
  coeff: T
}
impl<T: AD> DifferentiableFunctionTrait<T> for Test<T> {
  const NAME: &'static str = "Test";

  fn call(&self, inputs: &[T], _freeze: bool) -> Vec<T> {
    vec![ self.coeff*inputs[0].sin() + inputs[1].cos() ]
  }

  fn num_inputs(&self) -> usize {
    2
  }

  fn num_outputs(&self) -> usize {
    1
  }
}
impl<T: AD> Test<T> {
  pub fn to_other_ad_type<T2: AD>(&self) -> Test<T2> {
    Test { coeff: self.coeff.to_other_ad_type::<T2>() }
  }
}


fn main() {
  let inputs = vec![1., 2.];

  // Reverse AD //////////////////////////////////////////////////////////////////////////////////
  let function_standard = Test { coeff: 2.0 };
  let function_derivative = function_standard.to_other_ad_type::<adr>();
  let differentiable_block = FunctionEngine::new(function_standard, function_derivative, ReverseAD::new());

  let (f_res, derivative_res) = differentiable_block.derivative(&inputs);
  println!("Reverse AD: ");
  println!("  f_res: {}", f_res[0]);
  println!("  derivative: {}", derivative_res);
  println!("//////////////");
  println!();

  // Forward AD //////////////////////////////////////////////////////////////////////////////////
  let function_standard = Test { coeff: 2.0 };
  let function_derivative = function_standard.to_other_ad_type::<adfn<1>>();
  let differentiable_block = FunctionEngine::new(function_standard, function_derivative, ForwardAD::new());

  let (f_res, derivative_res) = differentiable_block.derivative(&inputs);
  println!("Forward AD: ");
  println!("  f_res: {}", f_res[0]);
  println!("  derivative: {}", derivative_res);
  println!("//////////////");
  println!();

  // Forward AD Multi ////////////////////////////////////////////////////////////////////////////
  let function_standard = Test { coeff: 2.0 };
  let function_derivative = function_standard.to_other_ad_type::<adfn<2>>();
  let differentiable_block = FunctionEngine::new(function_standard, function_derivative, ForwardADMulti::new());

  let (f_res, derivative_res) = differentiable_block.derivative(&inputs);
  println!("Forward AD Multi: ");
  println!("  f_res: {}", f_res[0]);
  println!("  derivative: {}", derivative_res);
  println!("//////////////");
  println!();

  // Finite Differencing /////////////////////////////////////////////////////////////////////////
  let function_standard = Test { coeff: 2.0 };
  let function_derivative = function_standard.clone();
  let differentiable_block = FunctionEngine::new(function_standard, function_derivative, FiniteDifferencing::new());

  let (f_res, derivative_res) = differentiable_block.derivative(&inputs);
  println!("Finite Differencing: ");
  println!("  f_res: {}", f_res[0]);
  println!("  derivative: {}", derivative_res);
  println!("//////////////");
  println!();

  // Second-Order Derivatives (Hessian) //////////////////////////////////////////////////////////
  // Using HessianAD for Forward-over-Forward Hessian
  use ad_trait::differentiable_function::HessianAD;
  let function_standard = Test { coeff: 2.0 };
  let function_derivative = function_standard.to_other_ad_type::<HyperAD_ADFN<1>>();
  let differentiable_block = FunctionEngine::new(function_standard, function_derivative, HessianAD::<1>::new());

  let (f_res, jacobian_res, hessian_res) = differentiable_block.hessian(&inputs);
  println!("Second-Order AD: ");
  println!("  f_res: {}", f_res[0]);
  println!("  jacobian: {}", jacobian_res);
  println!("  hessian: {:?}", hessian_res);
  println!("//////////////");
  println!();
}

Changelog

[0.3.1]
  • Performance Optimizations: Dramatically improved execution speeds for Reverse AD, Forward AD, and Hessian AD (HessianAD_FOR mode) without any breaking API changes.
  • Optimized Reverse AD (adr): Reduced computation graph node size by 55% (from 88 to 40 bytes) and replaced thread-local RwLock operations with zero-overhead RefCell/Cell structures.
  • Optimized Forward AD (adf): Eliminated heap allocations during SIMD multi-tangent operations in favor of stack arrays, allowing the compiler to autovectorize calculations directly into hardware registers.
  • Accelerated Hessian AD (HessianAD_FOR): Sped up Forward-over-Reverse Hessian computations by utilizing the optimized reverse AD engine.
  • Stable Forward AD (adfn): Confirmed that adfn runs entirely on stable Rust (no nightly compiler required). Because adfn uses stack-allocated arrays [f64; N], it was already zero-allocation and did not require changes.
Performance Benchmarks (Macbook Air M3)
AD ModeFunctionIterationsOriginal TimeOptimized TimeSpeedup Factor
Reverse ADRosenbrock (10 inputs)100,000118.36 ms81.55 ms1.45x
Reverse ADPolynomial (1 input)1,000,00094.10 ms60.44 ms1.56x
Reverse ADMultivariate (2 inputs)1,000,000152.50 ms103.57 ms1.47x
Forward ADMath Heavy (f64x8)1,000,0001.12 s529.49 ms2.12x
Hessian AD ($N=1$)Rosenbrock (10 inputs)1,00066.67 ms49.20 ms1.36x
Hessian AD ($N=2$)Rosenbrock (10 inputs)1,00057.76 ms40.97 ms1.41x
Hessian AD ($N=5$)Rosenbrock (10 inputs)1,00055.85 ms41.38 ms1.35x
Hessian AD ($N=10$)Rosenbrock (10 inputs)1,00069.88 ms48.03 ms1.46x
Hessian AD ($N=1$)Polynomial (1 input)10,0006.13 ms5.49 ms1.12x
Hessian AD ($N=1$)Multivariate (2 inputs)10,00011.89 ms9.89 ms1.20x
Hessian AD ($N=2$)Multivariate (2 inputs)10,00010.64 ms8.65 ms1.23x
[0.3.0]
  • Second-Order AD: Added full support for computing Hessians via recursive dual types.
  • New AD Modes:
    • Forward-over-Forward: Using the new HyperAD_ADFN type.
    • Forward-over-Reverse: Using the new HyperAD_ADR type.
  • FunctionEngine Improvements:
    • Added a high-level .hessian() method to FunctionEngine for one-call value/gradient/Hessian evaluation.
    • Implemented automatic multi-pass batching for Hessian computation, allowing full Hessian recovery even when the number of tangent lanes is smaller than the input dimension.
  • Enhanced Diagnostics: Integrated #[diagnostic::on_unimplemented] to provide clear, actionable compiler error messages when calling Hessian methods on incompatible engines.
  • Stability: Promoted hessian features from experimental to a default library feature.
  • Documentation: Major updates to the ad_trait book with dedicated theory and implementation pages for second-order derivatives.

Citation

For more information about our work, refer to our paper: https://arxiv.org/abs/2504.15976

If you use this crate in your research, please cite:

@article{liang2025ad,
  title={ad-trait: A fast and flexible automatic differentiation library in rust},
  author={Liang, Chen and Wang, Qian and Xu, Andy and Rakita, Daniel},
  journal={arXiv preprint arXiv:2504.15976},
  year={2025}
}
Runs on
GPU support unknown
What shows it
  • no dependency or feature matches a backend row
Native code
None found
  • No native code found
Python bindings
No Python binding crate found
License
Apache-2.0 OR MIT

Compare with similar projects

Order: strongest tier first, then most downloads, then name, with unmeasured values last. A library counts downloads over 30 days. An app counts binary downloads per release. An app with none counts its crate downloads over 30 days. ML Rust runs this catalogue, so its closest project always gets a row.

ad_trait beside the projects that share a topic with it
ProjectDownloadsDependentsStarsLatest releaseRuns on (GPU)Native codeLicense
ad_trait This page Listed

Easy to use, efficient, and highly flexible automatic differentiation in Rust

2,070 downloads over 30 days 2 24 0.3.1 GPU support unknown No native code found Apache-2.0 OR MIT
peroxide Listed

Rust comprehensive scientific computation library contains linear algebra, numerical analysis, statistics and machine learning tools with familiar syntax

Python bindings

56,548 downloads over 30 days 9 732 0.43.1 GPU support unknown Binds native code: openblas-src (feature O3-openblas-system), blas-sys (feature O3), hdf5-metno-sys (feature nc), lapack-sys (feature O3), libz-sys (feature nc) and 1 more Apache-2.0 OR MIT
basin Listed

Numerical optimization in pure Rust, with pluggable linear-algebra backends and WASM support.

22,519 downloads over 30 days 9 128 3.2.0 GPU support unknown Binds native code: blas-sys (feature nalgebra_latest-lapack), lapack-sys (feature nalgebra_latest-lapack) Apache-2.0 OR MIT
numr Listed

The base for numerical code in Rust, in the role NumPy has in Python: n-dimensional tensors, linear algebra, FFT, statistics and autograd on CPU, CUDA and WebGPU. The backends use native kernels, with no cuBLAS, MKL or other vendor math library.

1,673 downloads over 30 days 7 59 0.15.2 CUDA, WebGPU Binds native code: ring (feature distributed) Apache-2.0
scirs Listed

A Rust port of SciPy with AI/ML extensions - Scientific Computing and AI Library (scirs2)

Python bindings

117 downloads over 30 days 198 306 0.6.5 CUDA, WebGPU, Metal, ROCm, Vulkan Binds native code: perf-event-open-sys (feature profiling_perf). Build uses a native toolchain: cc (feature c-opt) Apache-2.0
rapl Listed

A crate that makes numerical scripting with Rust simple and enjoyable.

21 downloads over 30 days 1 107 0.4.0 GPU support unknown No native code found MIT
Why ListedNo archive, New or Featured rule places it, so it is Listed.

What it lacks for Featured

  • It has 2 active dependents and 2 new dependents in 365 days. Featured needs 11 active dependents or 9 new dependents in 365 days. The repository route reads 24 stars, 9 forks and 2 contributors. It needs 4,539 stars, 434 forks and 79 contributors together.

What else the check found

  • The last activity is on 23 May 2026, 170 days ago. The rules expect an update within 365 days. Dormancy rule

Exact rules: Listed, Featured library. The check on applied thresholds version 9.

Every rule outcome, as the check records it
  • expected-interval: version 0.3.1 base 300, raised to the 365-day floor: E = 365 days
  • dormancy: last activity 2026-05-23, 170 days ago, E = 365: active
  • featured: not featured: active_users 2 < 11 and new_adopters 2 < 9 and repository route stars 24 (needs 4539), forks 9 (needs 434), contributors 2 (needs 79)
  • listed: listed: no archive, new or featured rule applies

Measurements and sources

Each signal row shows the raw value, its source and the fetch date. The Sources list gathers every distinct source on this page. Movement needs more history.

Sources6 sources
Adoption2 active dependents, 2 new dependents in 365 days1 not measured
Adoption measurements
SignalValueSourceFetchedCounts
Active dependents2crates.io database dumpYes
New dependents (365 days)2crates.io database dumpYes
Peak active dependents3crates.io database dumpYes
Active dependents as a share of the peak1crates.io database dumpYes
Binary downloads per releaseNot measuredYes
MaintenanceLatest human commit: 5 months ago3 not measured
Maintenance measurements
SignalValueSourceFetchedCounts
Latest human commit2026-05-23GitHub repositoryYes
Latest release2026-05-23crates.io database dumpYes
First release2025-05-12crates.io database dumpYes
Latest version0.3.1crates.io database dumpYes
Days the oldest outside issue waits for a reply0GitHub repositoryYes
Maintainer replies over 365 days3GitHub repositoryYes
Repository archivedfalseGitHub repositoryYes
Repository gonefalseGitHub repositoryYes
Release commit or manifest in the repotruecrates.io packageYes
Published docstruecrates.io database dumpYes
Latest release fails cargo checkNot measuredYes
Build check dateNot measuredYes
Build check toolchainNot measuredYes
SecurityUnpatched vulnerabilities: none
Security measurements
SignalValueSourceFetchedCounts
Unpatched vulnerabilities past the grace windownoneRustSec advisory databaseYes
RustSec unmaintained advisorynoneRustSec advisory databaseYes
Deprecation noticenonecrates.io database dumpYes
Deprecated requirementnonecrates.io database dumpYes
Distribution13 releases, 2,070 downloads over 30 days5 not measured
Distribution measurements
SignalValueSourceFetchedCounts
Releases13crates.io database dumpYes
Downloads over 30 days2070crates.io database dumpYes
Binary downloads over the last 3 releasesNot measuredYes
Homebrew installs on request over 365 daysNot measuredYes
Repology repository familiesNot measuredYes
Docker pull growth over 90 daysNot measuredYes
Docker pulls at the growth baselineNot measuredYes
Every version a prereleasefalsecrates.io database dumpYes
Every version 0.0.xfalsecrates.io database dumpYes
Every version yankedfalsecrates.io database dumpYes
Crate deleted from crates.iofalsecrates.io database dumpYes
Repository24 stars, 9 forks, 2 contributors, 96 commits. Stars alone never qualify a project.
Repository measurements
SignalValueSourceFetchedCounts
GitHub stars24GitHub repositoryYes — one part of the repository route
GitHub forks9GitHub repositoryYes — one part of the repository route
Contributors with a GitHub account2GitHub contributorsYes — one part of the repository route
Commits on the default branch96GitHub repositoryNo
Repository's main crate left out of the entrynonecrates.io database dumpYes
Facts that never count
Facts that never count measurements
SignalValueSourceFetchedCounts
LicenseApache-2.0 OR MITcrates.io database dumpNo
Runs on, from listed crates and their direct dependenciesGPU support unknowncrates.io database dumpNo
What shows each backendno dependency or feature matches a backend rowcrates.io database dumpNo
Native code, from listed crates and their dependenciesNo native code foundcrates.io database dumpNo
Python bindings, from direct dependencies of listed cratesNo Python binding crate foundcrates.io database dumpNo
Crates that depend on a listed crate directly2crates.io database dumpNo

Corrections and review history

Report a correction

No correction applies to this entry.

Judgments

A judgment enters only through an approved issue and a merged pull request.

No judgment applies to this entry.