ddx 5.5.0
dotnet add package ddx --version 5.5.0
NuGet\Install-Package ddx -Version 5.5.0
<PackageReference Include="ddx" Version="5.5.0" />
<PackageVersion Include="ddx" Version="5.5.0" />
<PackageReference Include="ddx" />
paket add ddx --version 5.5.0
#r "nuget: ddx, 5.5.0"
#:package ddx@5.5.0
#addin nuget:?package=ddx&version=5.5.0
#tool nuget:?package=ddx&version=5.5.0
ddx
A C++23 library for differentiating expressions. Build a function over named symbols while the program runs — terms looped over a data file, a model read from configuration, an expression typed by a user, a loss that switches shape on a comparison — and ask it for values, gradients, Jacobians and Hessians. One point at a time or a batch of thousands in one call, interpreted or compiled through LLVM. There are Python bindings over the same runtime, and a header-only compile-time API for expressions whose shape is known when you compile.
#include "ddx.hpp"
#include "rt/equation.hpp"
using namespace ddx;
struct Sample { double t, y; };
const std::vector<Sample> data{{0.0, 2.00}, {1.0, 1.21}, {2.0, 0.74}, {3.0, 0.45}};
// Huber loss of the fit m(t) = a·exp(−b·t).
const double delta = 0.05;
const auto eq = rt::equation([&] {
const auto a = rt::var("a");
const auto b = rt::var("b");
rt::Expression<double> loss = 0.0;
for (const auto &s : data) {
const auto r = s.y - a * exp(-b * s.t);
loss += select(abs(r) < delta, r * r, delta * (2.0 * abs(r) - delta));
}
return loss;
});
*eq.evaluate(2.0, 0.5); // 4.1343959887e-05
*eq.jacobian(2.0, 0.5); // {-0.0010757424682, 0.0150678475595}
*eq.hessian(2.0, 0.5); // 2 × 2, row-major
Install
GCC 14+, Clang 20+ over libstdc++ 14+ (not libc++), or MSVC 2022 with
/std:c++latest; CMake 3.26+. Boost and GoogleTest are fetched at configure
time.
add_subdirectory(ddx)
target_link_libraries(my_app PRIVATE ddx::rt) # or ddx::jit
find_package(ddx CONFIG REQUIRED COMPONENTS rt jit)
| Target | Is |
|---|---|
ddx::ddx |
header-only: compile-time expressions |
ddx::rt |
runtime equations |
ddx::jit |
ddx::rt with the LLVM backend (-DDDX_BUILD_JIT=ON, needs an installed LLVM 20; ddx never downloads it) |
Conan: conan create . packages it and conan editable add . uses the tree
in place; consumers find_package(ddx) as above. -o "ddx/*:jit=True" adds
the JIT, with Conan building LLVM 20 from contrib/conan
(conan remote add ddx contrib/conan --type=local-recipes-index). Also
packaged for vcpkg (--overlay-ports=contrib/vcpkg/ports) and NuGet (ddx),
neither with the JIT. Presets: debug, release, debug_jit,
release_jit, python.
Equations
rt::equation(callback) runs the callback and returns the equation. Symbols are
named inside it with rt::var(name) — any run-time string — and are ordered as
first named; that order is the order of points and results.
const auto f = rt::equation([] { return exp(rt::var("x")) * sin(rt::var("y")); });
// A system: return an array (count in the type) or a vector (rt::System).
const auto sys = rt::equation([] {
const auto x = rt::var("x");
const auto y = rt::var("y");
return std::array{x * y + sin(x), exp(x) - y * y};
});
Name symbols in separate statements when order matters — C++ leaves argument
evaluation order unspecified. Another scalar type: rt::equation<T> with
rt::var<T>.
| Inside the callback | Is |
|---|---|
rt::var(name) |
a symbol: differentiated |
rt::param(name) |
an input that is read, never differentiated |
rt::implicit(name, [&](auto z) { return F; }) |
an input that is a root of F; derivatives carry ∂z/∂x = −F_x/F_z |
rt::extern_fn({.name, .arity, .order}, fn) |
your own function; fn(in, out) writes the value, then the partials (upper triangle of the second at order = 2) |
rt::vec(name, n), rt::vec_constant(data), rt::mat_constant(r, c, data), rt::pack({…}), rt::outer(u, w) |
vectors and matrices (rt/tensor.hpp): n ordinary symbols as one node |
A point supplies symbols, then parameters, then implicits. eq.residual(point)
evaluates each implicit's F; ddx never solves it.
Vectors are elementwise under every operation, with sum, dot and
gemv(M, v, transposed = false), and % spells both: u % v is dot(u, v),
M % v is gemv(M, v) and rt::transpose(M) % v is gemv(M, v, true),
bit for bit (@ in Python). v[i] reads one element. select over vectors
and matrices takes the whole arm under a scalar condition and element by
element under a condition of the arms' shape, a scalar arm taking the other's
shape; the arm not taken never reaches a derivative, even where it is
infinite. They compute at
the equation's scalar (double or float), are never an output, and,
interpreted, are computed by a kernel table of that scalar — rt::use_tensor_kernels(table) or
eq.tensor_kernels(table), built with rt::tensor_kernel_table<K, T>() over a
type satisfying rt::TensorKernels<K, T> (T defaults to double). Inherit
rt::reference::Kernels<T> and replace only the rows your library does better;
tests/eigen and tests/cblas each hold one, Eigen and any CBLAS, at both
scalars. Each scalar has its own process default, rt::tensor_kernels<T>():
struct Blas : rt::reference::Kernels<> {
static constexpr std::string_view name = "cblas";
static void gemv(std::size_t r, std::size_t c, In m, In v, Out out, bool t) noexcept {
cblas_dgemv(CblasColMajor, t ? CblasTrans : CblasNoTrans, int(r), int(c), 1.0,
m.data(), int(r), v.data(), 1, 0.0, out.data(), 1);
}
};
constexpr auto blas = rt::tensor_kernel_table<Blas>();
rt::use_tensor_kernels(blas); // a float table, built over Kernels<float>, sets float's
Matrices are elementwise the same way: a mat_constant table taking part in
arithmetic is its matrix, so exp(-(A0 + T * A1) / (R * T)) over tables is a
matrix of T computed in a few nodes, and gemv(M, v, transposed) and
dot(M, N) read it. rt::outer(u, w) is u wᵀ. Shapes must agree, rows and
columns both, and a scalar expression meets a matrix as a factor (T * B,
B / T), as it meets a vector. dense_hessian stays O(n²) over a matrix of tables,
parameters and scalar symbols: beside a vector x, each scalar var (T, P)
costs one more reverse sweep, and the block covers every symbol. A
matrix that moves with a symbol and is then multiplied (gemv(exp(outer(x, x)), x)) has no O(n²) form, and dense_hessian refuses it with
errc::dense_refused; hessian, hvp and jacobian_jvp answer it.
Expressions
| Kind | Available |
|---|---|
| Arithmetic | + - * / unary - += -= *= /= |
| Unary | sin cos tan exp log log10 sqrt cbrt abs sign asin acos atan sinh cosh tanh asinh acosh atanh erf |
| Binary | pow atan2 hypot max min |
| Comparison | < <= > >= == != — answer 1.0 or 0.0 |
| Conditional | select(cond, if_true, if_false) |
| Derivative | derivative(f, "x"), gradient(f) — expressions, to build on inside the lambda |
A loop of +=, *= or /= is stored as one node over all its terms, not a
chain of one node per step, so a long sum or product stays cheap to evaluate
and to differentiate; its value is the chain's, step for step.
select evaluates both arms and differentiates the taken one; the condition is
never differentiated. abs′(0) = 0, max/min split a tie in half, and
pow(0, b) has zero partials.
Points
*eq.jacobian(1.3, 0.7); // positional
*eq.jacobian(std::array{1.3, 0.7}); // any range
*eq.jacobian(named<"y">(0.7), named<"x">(1.3)); // by name
*eq.jacobian("y"_s = 0.7, "x"_s = 1.3);
*eq.jacobian(std::map<std::string, double>{{"y", 0.7}, {"x", 1.3}}); // varmap
A named point must name every input (errc::short_point). eq.point(args…)
builds the positional vector once for reuse.
Calls
Per-point calls answer result<T> (std::expected<T, ddx::error>); for
f: ℝⁿ → ℝᵐ:
| Call | Answers |
|---|---|
evaluate(x) |
f(x): T, or std::vector<T> for a system |
jacobian(x) |
J, row-major m × n — the gradient when m = 1 |
gradient(x) |
J without computing f |
hessian(x) |
dense m × n × n |
dense_hessian(x) |
n × n from one O(n²) sweep, for densely coupled vector models; one output |
jvp(v, x) |
J v, length m |
vjp(w, x) |
wᵀ J, length n |
hvp(v, x), hvp(name, x) |
H v, length n; one output |
jacobian_jvp(v, x), jacobian_jvp(name, x) |
∂J/∂v, m × n |
univariate_derivative<K>(x0), univariate_derivative<K>(xs, out) |
K-th derivative; one symbol, one output; the span form fills out[i] at xs[i], several points to a sweep |
The batch calls take one input column per input and one output pointer per
output column, each n points long, write in place without allocating, and
answer result<void>:
eq.evaluate(xs, f, n);
eq.jacobian(xs, f, g, n);
eq.gradient(xs, g, n);
eq.hessian(xs, f, g, h, n);
eq.jvp(xs, vs, f, p, n);
eq.vjp(xs, ws, f, p, n);
eq.hvp(xs, vs, f, g, p, n);
eq.dense_hessian(xs, f, g, h, n);
eq.jacobian_jvp(xs, vs, f, g, dg, n);
Size each block with value_columns(), jacobian_columns(),
hessian_columns(), jvp_columns(), vjp_columns(), hvp_columns(),
dense_hessian_columns(). The Jacobian block holds only structural nonzeros —
jacobian_pattern() maps columns to cells — and the Hessian block is
colour-compressed, read with hessian_cell(i, j) or hessian_pattern().
A column-major matrix's columns are batch columns as they stand;
tests/eigen/tests_eigen.cpp passes Eigen matrices in and scatters blocks back
out dense.
eq.restrict({"T", "P"}) is a view computing only those symbols' Jacobian
columns.
Inspecting
| Member | Answers |
|---|---|
poisoned(), status() |
whether building failed, and the ddx::error |
arity(), outputs() |
symbol count n, function count m |
symbols(), params(), inputs(), input_count() |
names in declaration order |
prepare({rt::Want::Jacobian, …}) |
build those lanes up front |
census(want) |
the steps one call takes and the values they write, per opcode, counted before any point |
A poisoned equation answers every call with its error. errc and error
format and stream as text. Nothing throws.
All members are const and thread-safe except options() and tensor_kernels(table).
The equation owns everything it needs and is move-only; symbols are valid only
inside the callback that named them. Each thread keeps the tapes it sweeps into
at the largest size it has needed; rt::release_tapes() (Python
ddx.release_tapes()) frees the calling thread's, for a pool worker after a
large sweep.
Compiling
Link ddx::jit and set options; the same calls answer the same results.
Nothing compiles unless asked. Under Compile, the first call to each lane
(Jacobian, Hessian, …) builds that lane's kernel and waits for it:
eq.options({.backend = rt::Backend::Compile, .points = 4096});
eq.uses_kernel(); // optional: build the Jacobian kernel now; true
eq.compile_status(); // the same, with the JIT's error when it refused
eq.jacobian(xs, f, g, n); // compiled
Backend |
Is |
|---|---|
Interpret |
default; LLVM is never loaded |
Compile |
compile each lane on its first call |
jit::Options field |
Default | Is |
|---|---|---|
backend |
Interpret |
as above |
points |
1 |
the batch size one call will carry |
codegen.lanes |
Lanes::derived() |
points per iteration |
codegen.opt_level, codegen.codegen_level |
build type, O1 |
LLVM levels; codegen_level moves compile time |
codegen.slp_vectorize |
false |
extra vectorisation |
codegen.veclib |
None |
Libmvec for vector transcendentals |
codegen.contract |
DDX_FP_FLAGS |
fuse multiply-add |
A model with vectors compiles too. Each vector operation is a loop in the kernel, vectorised by LLVM, and an elementwise operation read once is computed inside its reader's loop rather than stored; only the dense Hessian's matrix products still go through the interpreter. The kernel's sums take their own order, so a compiled answer agrees with the interpreted one to a few ulps rather than to the bit, and a kernel table computes the interpreted sweep only.
Python
pip install ddx-ad
import ddx
@ddx.equation
def f():
x = ddx.var("x")
y = ddx.var("y")
return ddx.exp(x) * ddx.sin(y)
value, gradient = f.jacobian([2.0, 3.0])
Wheels for Linux x86_64 and Windows x64, both with the JIT, CPython 3.11–3.14. See python/README.md.
Compile-time expressions
Header-only; symbols are template arguments, results are std::arrays or
tensors, and all but hessian are constexpr:
constexpr auto x = var<"x">;
constexpr auto y = var<"y">;
constexpr auto eq = Equation{x * y + 2.0 * x};
static_assert(eq.jacobian(2.0, 3.0)[0] == 5.0);
Equation{x * y}.hessian(2.0, 3.0); // links ddx::rt
Equation{x * y}.derivative_tensor<3>(1.0, 2.0); // rank 3
Equation{sin(x)}.univariate_derivative<4>(0.5);
std::format("{}", x * y + sin(x)); // "x * y + sin(x)"
std::format("{}", Equation{x * y}); // "f0: x * y\n jac: y, x\n"
Forward duals
ddx::nth_dual<T, N> is a number with N nested ε's: 2^N coefficients on the
stack, no allocation, every math function by ADL. dual_seed<N>(v, mask)
makes a variable that the ε's in mask differentiate by (bit 0 is the
outermost ε). dual_part<Mask>(f) reads the coefficient of those ε's.
using D = ddx::nth_dual<double, 3>;
const D T = ddx::dual_seed<3>(300.0, 0b001);
const D V = ddx::dual_seed<3>(1e-3, 0b010);
const D n = ddx::dual_seed<3>(2.0, 0b100);
const D A = helmholtz(T, V, n); // any function templated on its scalar
ddx::dual_part<0b000>(A); // A
ddx::dual_part<0b011>(A); // ∂²A/∂T∂V
ddx::dual_part<0b111>(A); // ∂³A/∂T∂V∂n
Seeding one variable on every ε (mask = 0b111) gives its third derivative in
dual_part<0b111>. ddx::dual and ddx::dual2nd are nth_dual<double, 1>
and nth_dual<double, 2>.
License
Boost Software License 1.0. Bundled third-party licences are in THIRD-PARTY-NOTICES.txt.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| native | native is compatible. |
This package has no dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 5.5.0 | 97 | 11/16/2026 |
| 5.4.1 | 103 | 11/9/2026 |
| 5.4.0 | 87 | 11/8/2026 |
| 5.3.0 | 92 | 11/8/2026 |
| 5.2.0 | 108 | 11/5/2026 |
| 5.1.0 | 106 | 11/2/2026 |
| 5.0.1 | 111 | 11/2/2026 |
| 5.0.0 | 123 | 10/28/2026 |
| 4.3.0 | 128 | 10/25/2026 |
| 4.2.0 | 125 | 10/25/2026 |
| 4.0.0 | 124 | 10/24/2026 |
| 3.2.0 | 121 | 10/19/2026 |
| 3.1.0 | 113 | 10/18/2026 |
| 3.0.0 | 119 | 10/18/2026 |
| 1.3.6 | 144 | 10/5/2026 |
| 1.3.5 | 122 | 9/28/2026 |
| 1.3.4 | 139 | 9/21/2026 |
| 1.3.3 | 212 | 9/14/2026 |
| 1.3.2 | 133 | 9/11/2026 |
| 1.3.1 | 121 | 9/11/2026 |