Skip to content
210 changes: 188 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,48 +1,191 @@
# `difflapack`

`difflapack`is a library that provides derivative of LAPACK routines from their reference implementation in [lapack](https://github.com/Reference-LAPACK/lapack) using the automatic differentiation tool [Tapenade](https://gitlab.inria.fr/tapenade/tapenade) in four modes: forward (`_d`), vector forward (`_dv`), reverse (`_b`), and vector reverse (`_bv`).
The compiled `libdifflapack` can be linked into applications that need derivatives of LAPACK operations for optimization, sensitivity analysis etc.
`difflapack` is a library that provides derivatives of LAPACK routines from their reference implementation in [LAPACK](https://github.com/Reference-LAPACK/lapack) in four modes: forward (`_d`), vector forward (`_dv`), reverse (`_b`), and vector reverse (`_bv`).
The derivative routines are implemented using known derivative formulae and can be linked into applications that need derivatives of LAPACK operations for optimization, sensitivity analysis, etc.

This work was inspired in part by a need to differentiate a Fortran code [HFBTHO](https://www.sciencedirect.com/science/article/abs/pii/S0010465525004564), that uses LAPACK and BLAS routines, and to use the differentiated application for gradient-based optimization.

## Using the pre-compiled library from your application
## Using the library from your application

Use the library the same way the tests do:
1. Call the differentiated routines from your application.
2. Include the right header/module.
3. Link your application with `libdifflapack` and the LAPACK (`liblapack`) and BLAS library (`librefblas`) libraries.
After building (see below), link your application with `libdifflapack`, LAPACK, and BLAS:

```bash
gfortran myapp.f90 -L/path/to/builddir -ldifflapack -L$LAPACKDIR -llapack -lrefblas
```

In your Fortran source, declare the differentiated routines with `external` — no module is needed:

```fortran
external :: dsyevr, dsyevr_d
```

**Calling convention:**

difflapack follows [Tapenade's calling convention](https://tapenade.gitlabpages.inria.fr/userdoc/build/html/tapenade/faq.html#diffvarsinit): each derivative array is placed directly after its primal argument, routines are suffixed `_d` (forward) / `_b` (reverse), and vector mode adds an extra leading dimension for directions with a trailing `ndir` parameter. difflapack uses `_dv` and `_bv` suffixes for the vector variants.

For example, `DSYEVR` becomes:

| Mode | Routine | Key additions |
|------|---------|---------------|
| Forward | `DSYEVR_D` | `ad` after `a`, `wd` after `w`, `zd` after `z`, `workd` after `work` |
| Vector forward | `DSYEVR_DV` | Same as `_D`, plus trailing `ndir` argument |
| Reverse | `DSYEVR_B` | Same companion names; `ad`/`wd`/`zd` carry adjoint (bar) values |
| Vector reverse | `DSYEVR_BV` | Same as `_B`, plus trailing `ndir` argument |

In scalar modes (`_D`, `_B`), companion arrays have the same shape as their primal.
In vector modes (`_DV`, `_BV`), companion arrays have an extra leading dimension `ndir` for the number of directions, e.g. if `a(lda, n)` then `ad(ndir, lda, n)`.

**Vector mode — handling multiple directions:**

Vector forward (`_DV`) computes `ndir` tangent directions simultaneously. Set `ad(idir, :, :)` to the tangent seed for direction `idir` before the call; on return `wd(idir, :)` and `zd(idir, :, :)` hold the corresponding tangent outputs.

Vector reverse (`_BV`) computes `ndir` adjoint (cotangent) projections simultaneously. Set `wd(idir, :)` and `zd(idir, :, :)` to the cotangent seeds; on return `ad(idir, :, :)` holds the adjoint of `a` for each direction.

### Example: forward-mode eigenvalue derivatives with `DSYEVR_D`

[`DSYEVR`](https://www.netlib.org/lapack/explore-html/d2/d8a/group__heevr_ga320e4e6e38df69bde1cbb86da4c3c46d.html) computes eigenvalues and (optionally) eigenvectors of a real symmetric matrix using the Relatively Robust Representations (RRR) algorithm.
`DSYEVR_D` is its forward-mode derivative: given a symmetric matrix `A` and a tangent perturbation `Ad`, it computes the eigenvalues, eigenvectors, and their derivatives (`wd`, `zd`) in a single call:

```fortran
program example_dsyevr_d
implicit none
integer, parameter :: n = 3, lda = n, ldz = n
double precision :: a(lda,n), ad(lda,n), w(n), wd(n), z(ldz,n), zd(ldz,n)
double precision, allocatable :: work(:), workd(:)
integer, allocatable :: iwork(:)
integer :: isuppz(2*n), info, lwork, liwork, m

! Set up a symmetric matrix (lower triangle)
a = 0.0d0
a(1,1) = 2.0d0
a(2,1) = 1.0d0; a(2,2) = 3.0d0
a(3,1) = 0.0d0; a(3,2) = 1.0d0; a(3,3) = 4.0d0

! Tangent direction: derivative of A w.r.t. some parameter
ad = 0.0d0
ad(1,1) = 1.0d0 ! dA/dp = perturbation in the (1,1) entry

! Query workspace
lwork = -1; liwork = -1
allocate(work(1), iwork(1))
call dsyevr('V','A','L', n, a, lda, 0d0, 0d0, 0, 0, &
0d0, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
lwork = int(work(1)); liwork = iwork(1)
deallocate(work, iwork)
allocate(work(lwork), workd(lwork), iwork(liwork))

! Compute eigenvalues, eigenvectors, AND their derivatives in one call
call dsyevr_d('V','A','L', n, a, ad, lda, 0d0, 0d0, 0, 0, &
0d0, m, w, wd, z, zd, ldz, isuppz, work, workd, lwork, &
iwork, liwork, info)

! wd(i) = d(lambda_i)/dp, zd(:,i) = d(z_i)/dp
print *, 'Eigenvalues:', w(1:m)
print *, 'dEigenvalues/dp:', wd(1:m)
end program
```

### Example: reverse-mode eigenvalue derivatives with `DSYEVR_B`

`DSYEVR_B` computes the adjoint (gradient) of `A` given adjoint seeds for the eigenvalues (`wd`) and eigenvectors (`zd`).
First call `DSYEVR` to get the primal eigenvalues and eigenvectors, then call `DSYEVR_B`:

**Calling convention (same as in the tests):**
TODO
```fortran
! ... (same matrix setup and workspace query as above) ...

***Handing directions in vector mode:***
TODO
! First compute the primal eigendecomposition
a = a_orig ! restore A (DSYEVR overwrites it)
call dsyevr('V','A','L', n, a, lda, 0d0, 0d0, 0, 0, &
0d0, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)

! Set adjoint seeds: e.g. gradient of loss w.r.t. eigenvalues
wd = 0.0d0
wd(1) = 1.0d0 ! d(loss)/d(lambda_1) = 1
zd = 0.0d0 ! no gradient contribution from eigenvectors

! Compute adjoint of A
a = a_orig
call dsyevr_b('V','A','L', n, a, ad, lda, 0d0, 0d0, 0, 0, &
0d0, m, w, wd, z, zd, ldz, isuppz, work, workd, lwork, &
iwork, liwork, info)

! ad(i,j) = d(loss)/d(A(i,j))
print *, 'Adjoint of A(1,:):', ad(1,1:n)
```

### Example: vector forward mode with `DSYEVR_DV`

`DSYEVR_DV` computes `ndir` tangent directions simultaneously. The derivative arrays have an extra leading dimension for the direction index:

```fortran
integer, parameter :: ndir = 2
double precision :: ad(ndir, lda, n), wd(ndir, n), zd(ndir, ldz, n)
double precision :: workd(ndir, lwork)

! Direction 1: perturb A(1,1)
ad = 0.0d0
ad(1, 1,1) = 1.0d0

! Direction 2: perturb A(2,1) and A(1,2) (symmetric)
ad(2, 2,1) = 1.0d0

call dsyevr_dv('V','A','L', n, a, ad, lda, 0d0, 0d0, 0, 0, &
0d0, m, w, wd, z, zd, ldz, isuppz, work, workd, lwork, &
iwork, liwork, info, ndir)

! wd(idir, i) = d(lambda_i) in direction idir
print *, 'dEigenvalues (dir 1):', wd(1, 1:m)
print *, 'dEigenvalues (dir 2):', wd(2, 1:m)
```

### Example: vector reverse mode with `DSYEVR_BV`

`DSYEVR_BV` computes `ndir` adjoint projections simultaneously:

```fortran
integer, parameter :: ndir = 2
double precision :: ad(ndir, lda, n), wd(ndir, n), zd(ndir, ldz, n)
double precision :: workd(ndir, lwork)

! Adjoint seed 1: gradient w.r.t. lambda_1
wd = 0.0d0; zd = 0.0d0
wd(1, 1) = 1.0d0

! Adjoint seed 2: gradient w.r.t. lambda_2
wd(2, 2) = 1.0d0

call dsyevr_bv('V','A','L', n, a, ad, lda, 0d0, 0d0, 0, 0, &
0d0, m, w, wd, z, zd, ldz, isuppz, work, workd, lwork, &
iwork, liwork, info, ndir)

! ad(idir, i, j) = d(loss)/d(A(i,j)) for adjoint seed idir
print *, 'Adjoint of A(1,:) (seed 1):', ad(1, 1, 1:n)
print *, 'Adjoint of A(1,:) (seed 2):', ad(2, 1, 1:n)
```

## Building the library (and tests)

You need **pre-generated** sources (from step 1). The build compiles them and links with a BLAS library and the Tapenade adStack runtime.
The build compiles the derivative source files in `LAPACK/src/` and links them with a LAPACK and BLAS library.

### Build with Meson (library and tests)
### Build with Meson (library only)

**Dependencies:**

- **Fortran compiler** (e.g. gfortran, ifort, ifx) and **C compiler** (e.g. gcc).
- **Fortran compiler** (e.g. gfortran, ifort, ifx).
- **LAPACK installation** — a built Reference LAPACK (or compatible) providing BLAS (e.g. `librefblas.a` or `libblas.a`). Set **`LAPACKDIR`** (or equivalent) so Meson can find it (see below).
- **Tapenade adStack** — the repo already contains `TAPENADE/adStack.c` and `TAPENADE/include/`; Meson compiles and links these automatically. No separate Tapenade install is required for the build.

**Configure and build from the project root:**

```bash
meson setup builddir -Dlibblas=refblas -Dlibblas=reflapack -Dlibblas_path=/path/to/blas/build -Dliblapack_path=/path/to/lapack/build
meson setup builddir -Dlibblas=refblas -Dliblapack=reflapack -Dlibblas_path=/path/to/blas/build -Dliblapack_path=/path/to/lapack/build
meson compile -C builddir
```

This produces `builddir/libdifflapack.a`.
The Meson build uses `LAPACK/meson.build`, compiles everything in `LAPACK/src/`;
it does **not** build the test executables (tests are built by the LAPACK Makefile in 2b if you use that).
it does **not** build the test executables (tests are built by the Make workflow below).

To also run the tests, use the LAPACK Makefile (2b) or run the test programs built there. To install the library:
To also run the tests, use the Make workflow below. To install the library:

```bash
meson install -C builddir --prefix /your/install
Expand All @@ -52,9 +195,9 @@ meson install -C builddir --prefix /your/install

**Dependencies:**

- **Fortran compiler** (e.g. gfortran) and **C compiler** (e.g. gcc).
- **Fortran compiler** (e.g. gfortran).
- **LAPACK installed** — build and install [Reference LAPACK](https://github.com/Reference-LAPACK/lapack) so that you have `liblapack`.
- **`LAPACKDIR`** — set to the directory where LAPACK was built (or where `liblapack.a` lives), so the linker can find `-lliblapack`:
- **`LAPACKDIR`** — set to the directory where LAPACK was built (or where `liblapack.a` lives), so the linker can find `-llapack`:
```bash
export LAPACKDIR=/path/to/lapack/build
```
Expand All @@ -71,12 +214,35 @@ This builds per-mode test executables in `build/`. Run tests:

```bash
./runscript.sh
# or run individual test executables, e.g. build/test_dsyevr, build/test_dsyevr_vector build/test_dsyevr_reverse build/test_dsyevr_reverse_vector
# or run individual test executables, e.g.:
# build/test_dsyevr_d (forward)
# build/test_dsyevr_dv (vector forward)
# build/test_dsyevr_b (reverse)
# build/test_dsyevr_bv (vector reverse)
```

## Coverage

93 base LAPACK routines are differentiated across single (S) and double (D) precision, in both real and complex arithmetic (C, Z), yielding 262 precision-specific routines. Each is provided in all four derivative modes, for a total of 1048 test cases validated against central finite differences. The covered families include:

| Family | Routines |
|--------|----------|
| Symmetric eigenvalue (standard) | `*SYEV*`, `*SPEV*`, `*SBEV*`, `*STEV*`, `*STEDC`, `*STEQR`, `*STERF`, `*STEBZ`, `*STEIN`, `*STEMR`, `*STEGR`, `*PTEQR` |
| Hermitian eigenvalue (standard) | `*HEEV*`, `*HPEV*`, `*HBEV*` |
| Symmetric eigenvalue (generalized) | `*SYGV*`, `*SPGV*`, `*SBGV*` |
| Hermitian eigenvalue (generalized) | `*HEGV*`, `*HPGV*`, `*HBGV*` |
| Non-symmetric eigenvalue / Schur | `*GEES*`, `*GEEV*` |
| SVD | `*GESVD`, `*GESDD` |
| Linear equations | `*GESV*`, `*GBSV*`, `*GTSV*`, `*POSV*`, `*PPSV*`, `*PBSV*`, `*PTSV*`, `*SYSV*`, `*SPSV*`, `*HESV*`, `*HPSV*` |
| Linear least squares | `*GELS`, `*GELSD`, `*GELSS`, `*GELST`, `*GELSY` |
| Matrix factorizations | `*GETRF`, `*POTRF`, `*SYTRF`, `*HETRF`, `*GETRI`, `*POTRI`, `*SYTRI`, `*HETRI` |
| Triangular solves | `*GETRS`, `*POTRS`, `*TRTRS` |

## Future work
There are several routines within LAPACK that are not differentiated with verification, which we plan to add.
There are additional LAPACK routines (e.g. generalized SVD, bidiagonal SVD, additional expert drivers) that we plan to differentiate and add.

## Acknowledgement
This work was supported in part by the Applied Mathematics activity within the U.S. Department of Energy, Office of Science, Office
of Advanced Scientific Computing Research Applied Mathematics, and Office of Nuclear Physics SciDAC program under Contract No. DE-AC02-06CH11357. This work was supported in part by NSF CSSI grant 2104068.

This package was developed in part with the help of LLMs from Cursor and Claude Code from Anthropic.
Loading