@certik, @yizhang and everyone_else_interested:
I think it would be of immense benefit and forward-thinking to have automatic differentiation built into the LFortran compiler as a first class citizen.
Based on:
its usefulness/utility in the present/future and even past
trend in (array) programming languages:
Julia
Dex
Futhark
Jax - Python library
a C++ proposal - not yet ratified
etc.
not playing catch-up again in the future as we currently are in Fortran to other languages.
For LLVM-based compilers (such as LFortran), it should be possible in principle to use Enzyme AD which performs the differentiation on the level of the LLVM IR.
There are issues open on AD at both the stdlib and J3 Fortran proposals repositories:
Leaving all implementation details aside, the part interesting for the Fortran community is how to embed AD within our source code. Here’s a non-exhaustive list of approaches:
a directive based formalism that co-exists independent of the base language
by introducing new commands (differentiate block construct + jacobian/hessian commands to retrieve the derivatives)
I think it’s probably wildly optimistic to expect that the Fortran Committee would ever add anything like this to the language. Getting it into a compiler (i.e. LFortran) is likely the only hope we have. I agree, Fortran needs this. Differentiation is such a huge component in so many areas of scientific and technical computing, and Fortran has fallen behind in this as in so much else.
Building AD adjoints for blas/lapack routines is the most needed but also most daunting task on this roadmap.The problem with compiler level AD is the lack of knowledge of non-scalar structure that is ubiquitous in numerical computing, as it is not able to see matrix/jacobian structures in dgtsv, dgbsv, dsysv etc. So even we support Enzyme out of box we’ll need augment it significantly to make it usable/scalable for everyday Fortran applications.