XAD documentation

AAD for quant finance

Adjoint algorithmic differentiation (AAD) gives the sensitivities of a price, or of any risk number, to all of its inputs in one backward pass. The cost is a small constant multiple of one pricing run, whether the trade depends on ten inputs or ten thousand. Bumping costs one or two pricing runs per input, and its results depend on the bump size. The price of AAD is memory: the operations of the pricing run are recorded on a tape.

XAD is a C++ library for AAD, with Python bindings. This page covers the cases that come up in pricing and risk code, the parts that need care in real code, and the XAD sample for each.

Where AAD pays off

Problem What AAD gives XAD sample
Risk of a trade or book to its curves and surfaces Delta to every curve point (and vega to every surface node) in one pass SwapPricer
Monte Carlo Greeks Pathwise Greeks with no bump-size noise, memory independent of the number of paths BasketMonteCarlo, LiborSwaptionPricer
PDE pricers Sensitivities to every point of a local volatility surface in one pass AmericanPDE
Gamma and cross-gamma The full second-order matrix in forward-over-adjoint mode CrossGamma
Model calibration The Jacobian of model prices with respect to model parameters, for Levenberg–Marquardt HestonCalibration, CurveFit
Risk through a solver (implied volatility, calibrated parameters) Sensitivities to market quotes without differentiating the solver loop ImpliedVolatility

XVA, initial margin (SIMM) and FRTB sensitivities are the same problems at portfolio scale: many market inputs, a few outputs, and the same numbers needed every day.

For a handful of inputs, forward mode or bumping can be enough. XAD's forward mode runs on the same templated code.

All Greeks of a pricer in one pass

Write the pricer as a template on the number type, then evaluate it once with XAD's adjoint type on a tape. Black-Scholes has closed-form Greeks, so every number can be checked:

#include <XAD/XAD.hpp>
template <class T>
T blackScholesCall(const T& S, const T& K, const T& r, const T& sigma, const T& t)
{
    T sd = sigma * sqrt(t);
    T d1 = (log(S / K) + (r + 0.5 * sigma * sigma) * t) / sd;
    T d2 = d1 - sd;
    T N1 = 0.5 * erfc(-d1 / sqrt(2.0));
    T N2 = 0.5 * erfc(-d2 / sqrt(2.0));
    return S * N1 - K * exp(-r * t) * N2;
}
int main()
{
    using mode = xad::adj<double>;
    using AD = mode::active_type;
    mode::tape_type tape;
    AD S = 100.0, K = 105.0, r = 0.03, sigma = 0.2, t = 1.0;
    tape.registerInput(S);
    tape.registerInput(r);
    tape.registerInput(sigma);
    tape.registerInput(t);
    tape.newRecording();
    AD price = blackScholesCall(S, K, r, sigma, t);
    tape.registerOutput(price);
    derivative(price) = 1.0;
    tape.computeAdjoints();
    double delta = derivative(S);
    double rho   = derivative(r);
    double vega  = derivative(sigma);
    double theta = -derivative(t);   // t is time to maturity
}

A pricer with thousands of inputs works the same way: register them, record once, and one call to computeAdjoints gives every sensitivity. The BlackScholesGreeks sample does this for calls and puts, in forward and adjoint mode, against the closed-form Greeks.

What needs care in real code

Memory and Monte Carlo

The tape holds every operation of the recording, so recording a whole Monte Carlo run can need far more memory than the pricer itself. Record one path (or a batch of paths), compute its adjoints, accumulate them, and clear the tape before the next. Memory then stays flat however many paths you run. For long time-stepping loops, such as a PDE solver or a long simulation, checkpointing stores the state at chosen steps and recomputes the steps in between during the backward pass.

Threads

The tape is not shared between threads. Give each thread its own tape, let each thread accumulate the adjoints of its paths, and sum them at the end. BasketMonteCarlo does this and checks that the threaded run gives the same Greeks as a single-threaded one.

Discontinuous payoffs

Digitals, barriers and exercise decisions are step functions of the inputs. Pathwise derivatives see a slope of zero on each side of the step and miss the jump, so AAD on the raw payoff gives wrong Greeks (bumping sees the jump, but its Greeks are very noisy). Replace the step by a smooth one of chosen width with XAD's smoothed functions, or use a payoff smoothing or likelihood-ratio method that suits the product.

Solvers and calibration

Do not record the iterations of a root finder or an optimiser on the tape. The tape grows with the number of iterations, and the derivatives of a stopped iteration need not match those of the solution. Solve in plain double, then use the implicit function theorem at the solution: one adjoint pass through the equations that hold at the root gives the sensitivities of the solution to its inputs. ImpliedVolatility shows this for an implied volatility solve. The same idea turns sensitivities to calibrated model parameters into sensitivities to the market quotes the model was calibrated to.

For a step with a known derivative, such as a linear solve, an external function supplies its adjoint directly, and the rest of the computation stays on the tape. AmericanPDE does this for the tridiagonal solve of each time step.

Portfolio and trade-level risk

One adjoint pass differentiates one output. For the risk of a portfolio, make its value the output: one pass gives the risk of the whole book. For the risk of every trade separately, run one pass per trade, or use vector adjoint mode to propagate several outputs in one pass.

Values that drop off the tape

A derivative goes silently missing when an active value is converted to double and back: a call to value(), a cast, or a third-party function that only takes double. Keep the whole path from inputs to output in the active type, or wrap the double code as an external function.

QuantLib

QuantLibAAD builds QuantLib with XAD's active type as its Real, so its pricing engines, term structures and models return their sensitivities by AAD. It shows XAD on a production-sized code base of several hundred thousand lines. There is a Python package too, and a practical guide with patterns for real QuantLib code.

ORE

ORE with AAD is a private fork of the Open Source Risk Engine with XAD built in, under its own annual subscription. It computes every XVA sensitivity in one pass: 151× faster than ORE's own bump and revalue on a desk-grade netting set, and up to 1,000× on multi-currency XVA with code generation. See ORE with AAD for the figures, the method, and how to ask for access.

Checking the results

Before relying on AAD Greeks, compare them once against central finite differences on a few inputs, with the same random numbers for Monte Carlo. They should agree to within the accuracy of the bump. When they do not, the cause is usually one of the cases above: a discontinuous payoff, a value that dropped off the tape, or a solver recorded on the tape.

Next steps

Questions or issues: GitHub Discussions · issues. Would you rather we AAD-enabled your code? Get a free speed-up estimate.