and Enzyme
Bringing deep learning and automatic differentiation
to Fortran Earth-system models

Workshop on Software Strategies for Sustainable Physical Modelling
ECMWF, Reading

Jack Atkinson

Principal Research Software Engineer
ICCS - University of Cambridge

Joe Wallwork

Senior Research Software Engineer
ICCS - University of Cambridge

2026-11-25

Precursors

Slides and Materials

To access links or follow on your own device these slides can be found at:
jackatkinson.net/slides

Licensing

Except where otherwise noted, these presentation materials are licensed under the Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0) License.

Vectors and icons by SVG Repo under CC0(1.0) or FontAwesome under SIL OFL 1.1

Motivation

  • Fortran remains the GOTO language for weather and climate (and other) scientific applications
    • Built-in support for array operations
    • Highly performant, yet readable
    • (despite?) backwards compatibility
    • Considerable societal inertia (?)
  • 40-60% of ICCS projects are Fortran-based
    • Software support to multiple scientific projects
    • CESM, ICON, UK Met Office, UKCA, GEOS-Chem, …
    • Overlapping with a heavy ML focus

Fortran logo from fortran-lang/assets, MIT licence. ICCS logo © ICCS, University of Cambridge.

Hybrid Modelling

Neural Net by 3Blue1Brown under fair dealing.

Language interoperation

Many large scientific models are written in Fortran (or C, or C++).
Much machine learning is conducted in Python.

NCAR logo © UCAR.
PyTorch, the PyTorch logo and any related marks are trademarks of The Linux Foundation
Mathematical Bridge by cmglee used under CC BY-SA 3.0

FTorch

Approach

  • PyTorch has a C++ backend (libtorch) that provides an API.
  • Binding Fortran to C is straightforward1 from 2003 using iso_c_binding.

We therefore:

  • Save PyTorch models in a portable TorchScript format to be run by libtorch C++
  • Provide a Fortran API wrapping the libtorch C++ API,
    abstracting complex details from users

Example: Fortran Inference

use ftorch

implicit none

real, dimension(5), target :: in_data, out_data  ! Fortran data structures

type(torch_tensor), dimension(1) :: input_tensors, output_tensors
type(torch_model) :: torch_net

in_data = ...  ! Prepare data in Fortran

! Create Torch input/output tensors from the Fortran arrays
call torch_tensor_from_array(input_tensors(1), in_data, torch_kCPU)
call torch_tensor_from_array(output_tensors(1), out_data, torch_kCPU)

call torch_model_load(torch_net, 'path/to/saved/model.pt', torch_kCPU)  ! Load ML model
call torch_model_forward(torch_net, input_tensors, output_tensors)      ! Infer

call further_code(out_data)  ! Use output data in Fortran immediately

Key points

  • No-copy access to Fortran memory (CPU)
  • Multiple GPU backends supported through native Torch implementations
    • CUDA, HIP, XPU, MPS with multiple devices
  • Row-major/column-major handled via Torch strided accessor1


/Cambridge-ICCS/FTorch


I could talk for an hour in detail, see jackatkinson.net/slides or come chat.

Usage: Climate and beyond

  • E3SM - emulation of cloud-resolving models (Hu et al. 2025)
  • UKAEA - surrogate models for turbulent transport in fusion (JINTRAC), ~100x speedup
  • LS-DYNA - RNN constitutive model for bone in an explicit FEM solver (Saenz-Betancourt et al. 2027)
  • …


More at cambridge-iccs.github.io/FTorch/community/case_studies

CESM-MLe

  • The Community Earth System Model
  • FTorch integrated into the build system (CIME)
  • Selected as the ML interface for the ML-Enhanced CESM (CESM-MLe)
    • Provides a streamlined route for research to ESM
  • ICCS are providing ongoing support for:
    • CESM FTorch interface
    • CESM-MLe release
      • QA and gathering of parameterisations
    • Implementation of non-local schemes

ICCS logo - ICCS, University of Cambridge. M2LInES logo © M²LInES. LEAP logo © LEAP. NCAR logo © NCAR.

Why is FTorch a success?

  • Target 2 types of efficiency
    • Computational
    • Developer
  • RSE expertise in collaboration with scientists
    • requirements come from real model-development/research
    • we have the skills to build the tools that are needed
  • Extensive examples, documentation, community support, and outreach
  • An open, useable solution to a shared problem

Automatic differentiation in FTorch

FTorch originally focussed on deploying models trained offline.

However, it is clear (Mansfield and Sheshadri 2024) that attention to online performance is important.

Utilise Torch’s autograd machinery on torch_tensors:

  • Expose Torch autograd, optimzers, loss functions
  • Overload operators (=,+,-,*,/,**)


Making an entire model differentiable with FTorch would be invasive and we do not advocate for this…

Enzyme: AD for existing Fortran

Work led by Joe Wallwork.

Automatic Differentiation and Fortran

  • Strong history of AD in Fortran
    • traditionally time-intensive to add to a codebase
    • Tapenade (Source generation via chain rule)
    • hand-written derivatives e.g. Data Assimilation
  • Years of investment developing and optimising models
    • a rewrite risks losing this accumulated investment
  • Claim: Enzyme allows us to keep it all
    • small changes to existing source to get a differentiable model

LLVM and Enzyme

LLVM

  • Compiler toolchain
  • Source compiled to an intermediate representation (IR)
  • IR compiled to executables
  • llvm.org
  • Flang is the Fortran compiler1

Enzyme

Enzyme logo from enzyme.mit.edu, used with permission. LLVM logo from llvm.org.

Example - Square

  • Compute the square

  • Output:

    9.
program main



  implicit none
  real :: x, dx

  x = 3
  print *, square(x)




contains

  real function square(x)
    implicit none
    real, intent(in) :: x
    square = x**2
  end function square

end program main

Example - Add Enzyme

  • Use enzyme module and add a hook for calculating the derivative.
  • Enzyme uses iso_c_binding
  • The deriviative is always a
    subroutine/void
    • but functions and subroutines can be differentiated
program main

  use enzyme, only: enzyme_autodiff

  implicit none
  real :: x, dx

  x = 3
  print *, square(x)
  dx = 0
  call enzyme_autodiff(square, x, dx)
  print *, dx

contains

  real function square(x)
    implicit none
    real, intent(in) :: x
    square = x**2
  end function square

end program main

Example - Generate IR

  • Generate LLVM Intermediate Representation (IR) with flang:

    flang square.f90 -S -emit-llvm \
        -I /.../Enzyme/build/modules -o input.ll
  • The call to Enzyme is an unresolved declaration at this stage:
    call void @f__enzyme_autodiff_(...)

...

define void @_QQmain() #0 {
  %1 = alloca float, i64 1, align 4
  %2 = alloca float, i64 1, align 4
  store float 3.000000e+00, ptr %1, align 4
  %3 = call ptr @_FortranAioBeginExternalListOutput(i32 6, ptr @_QQclX2F776F726B2F7371756172652E66393000, i32 7)
  %4 = call contract float @_QFPsquare(ptr %1)
  %5 = call i1 @_FortranAioOutputReal32(ptr %3, float %4)
  %6 = call i32 @_FortranAioEndIoStatement(ptr %3)
  store float 0.000000e+00, ptr %2, align 4
  call void @f__enzyme_autodiff_(ptr @_QFPsquare, ptr %1, ptr %2)
  %7 = call ptr @_FortranAioBeginExternalListOutput(i32 6, ptr @_QQclX2F776F726B2F7371756172652E66393000, i32 10)
  %8 = load float, ptr %2, align 4
  %9 = call i1 @_FortranAioOutputReal32(ptr %7, float %8)
  %10 = call i32 @_FortranAioEndIoStatement(ptr %7)
  ret void
}

...

Example - Apply Enzyme

  • Run the Enzyme pass over the IR with opt:

    opt input.ll -S \
        -load-pass-plugin=/.../FlangEnzyme.so \
        -passes=enzyme \
        -o output.ll
  • The pass:

    • synthesises a new derivative function, and
    • replaces the placeholder call
    • @f__enzyme_autodiff_ becomes @diffe_QFPsquare
...

define void @_QQmain() #0 {
  %1 = alloca float, i64 1, align 4
  %2 = alloca float, i64 1, align 4
  store float 3.000000e+00, ptr %1, align 4
  %3 = call ptr @_FortranAioBeginExternalListOutput(i32 6, ptr @_QQclX2F776F726B2F7371756172652E66393000, i32 7)
  %4 = call contract float @_QFPsquare(ptr %1)
  %5 = call i1 @_FortranAioOutputReal32(ptr %3, float %4)
  %6 = call i32 @_FortranAioEndIoStatement(ptr %3)
  store float 0.000000e+00, ptr %2, align 4
  call void @diffe_QFPsquare(ptr %1, ptr %2, float 1.000000e+00)
  %7 = call ptr @_FortranAioBeginExternalListOutput(i32 6, ptr @_QQclX2F776F726B2F7371756172652E66393000, i32 10)
  %8 = load float, ptr %2, align 4
  %9 = call i1 @_FortranAioOutputReal32(ptr %7, float %8)
  %10 = call i32 @_FortranAioEndIoStatement(ptr %7)
  ret void
}

...

define internal void @diffe_QFPsquare(ptr noalias readonly captures(none) %0, ptr captures(none) %"'", float %differeturn) #5 {
  %"'de" = alloca float, align 4
  store float 0.000000e+00, ptr %"'de", align 4
  %"'de1" = alloca float, align 4
  store float 0.000000e+00, ptr %"'de1", align 4
  %2 = load float, ptr %0, align 4, !alias.scope !4, !noalias !7
  br label %invert

...

Example - Optimise

  • Apply optimisations to the original and differentiated code with opt:

    opt output.ll -S -O2 -o output_opt.ll
  • Optimisations to Existing Fortran code are preserved.

...

define void @_QQmain() local_unnamed_addr #0 {
  %1 = tail call ptr @_FortranAioBeginExternalListOutput(i32 6, ptr nonnull @_QQclX2F776F726B2F7371756172652E66393000, i32 7)
  %2 = tail call i1 @_FortranAioOutputReal32(ptr %1, float 9.000000e+00)
  %3 = tail call i32 @_FortranAioEndIoStatement(ptr %1)
  %4 = tail call ptr @_FortranAioBeginExternalListOutput(i32 6, ptr nonnull @_QQclX2F776F726B2F7371756172652E66393000, i32 10)
  %5 = tail call i1 @_FortranAioOutputReal32(ptr %4, float 6.000000e+00)
  %6 = tail call i32 @_FortranAioEndIoStatement(ptr %4)
  ret void
}

- Note the values have become hardcoded here!
...

Example - Compile and run

  • Compile the optimised LLVM IR to an executable:

    flang output_opt.ll -o square
  • Run:

    ./square
  • Output:

    9.
    6.

    d square/dx = 2 * x = 6.0 as expected!

  • Multiple-file compilation is possible with LTO:

    flang -flto -c \
        -I /.../Enzyme/build/modules square_mod.f90 \
        -o square_mod.o
    
    flang -flto -c \
        -I /.../Enzyme/build/modules main.f90 \
        -o main.o
    
    flang -flto -fuse-ld=lld -Wl, \
        --load-pass-plugin=/.../FlangEnzyme.so \
        square_mod.o main.o -o square

Enzyme logo from enzyme.mit.edu, used with permission. LLVM logo from llvm.org.

Enzyme - Other Notes

  • Both approaches to AD are catered for:
    • __enzyme_autodiff provides reverse mode,
    • __enzyme_fwddiff provides forwards mode
  • Custom derivatives can be supplied for specific operations
  • Activity descriptors to control arguments:
    • enzyme_const - constants with no derivative
    • enzyme_dup - duplicated arguments
  • Examples, tests, and docs added for Fortran:
    enzyme.mit.edu/getting_started/FortranGuide

Application: MITgcm

  • MITgcm differentiated in forward and reverse mode
    • validated against previous Tapenade and TAF (Gaikwad et al. 2025)
    • 1.4–2.3x faster than Tapenade, 25–40% more memory usage

MITGCM results figure courtesy of Joe Wallwork, ICCS.

Agent Skills

We publish and maintain SKILLs for our (and others’) software.

/Cambridge-ICCS/ICCS-SKILLS

Screenshot: Cambridge-ICCS/ICCS-SKILLS (MIT licensed).

Shameless Plug


Better software, better research?
The role of research software engineering in enhancing open science across disciplines



  • EGU27 4–9 April 2027, Vienna and online
  • Abstract submission open now: EGU27 session GS4.7
  • Deadline 12th January 2027
  • Geoscience and Society => submit here and a scientific session

Some thoughts

  • Aim to build tools that are useful beyond yourself
    • as widely as possible, across domains
  • The best work comes from community efforts
    • Sharing ideas and expertise
  • Good work comes from knowing what questions to ask
    • This comes from varied expertise and experience
  • The easiest tool can beat the best tool
    • Docs, tests, examples are more important than ever…
    • with less of an excuse than ever.
    • As is technological governance.
  • The front moves fast, the air mass slower
    • Nothing will be replaced everywhere immediately
    • Accelerating R2O remains important

Thanks for Listening


Thanks to Mikolaj Kowalski, Valentin Churavy,
Tom Meltzer, Isaac Akanho, and all of the ICCS team.

The ICCS received support from

FTorch has been supported by

Logos: Schmidt Futures, C2D3, Cambridge-ICCS/FTorch, enzyme.mit.edu, and ICCS — University of Cambridge.

References

Gaikwad, Shreyas Sunil, Sri Hari Krishna Narayanan, Laurent Hascoët, Jean-Michel Campin, Helen Pillar, An Nguyen, Jan Hückelheim, Paul Hovland, and Patrick Heimbach. 2025. “MITgcm-AD V2: Open Source Tangent Linear and Adjoint Modeling Framework for the Oceans and Atmosphere Enabled by the Automatic Differentiation Tool Tapenade.” Future Generation Computer Systems 163: 107512. https://doi.org/10.1016/j.future.2024.107512.
Hu, Zeyuan, Akshay Subramaniam, Zhiming Kuang, Jerry Lin, Sungduk Yu, Walter M Hannah, Noah D Brenowitz, Josh Romero, and Michael S Pritchard. 2025. “Stable Machine-Learning Parameterization of Subgrid Processes in a Comprehensive Atmospheric Model Learned from Embedded Convection-Permitting Simulations.” Journal of Advances in Modeling Earth Systems 17 (7): e2024MS004618. https://doi.org/10.1029/2024MS004618.
Ikuyajolu, Olawale James, Luke P Van Roekel, Steven R Brus, and Erin E Thomas. 2026. “NLML: A Deep Neural Network Emulator for the Exact Nonlinear Interactions in a Wind Wave Model.” Journal of Geophysical Research: Machine Learning and Computation 3 (1). https://doi.org/10.1029/2025JH000699.
Mansfield, Laura A, and Aditi Sheshadri. 2024. “Uncertainty Quantification of a Machine Learning Subgrid-Scale Parameterization for Atmospheric Gravity Waves.” Journal of Advances in Modeling Earth Systems 16 (7): e2024MS004292. https://doi.org/10.1029/2024MS004292.
Moses, William S., and Valentin Churavy. 2020. “Instead of Rewriting Foreign Code for Machine Learning, Automatically Synthesize Fast Gradients.” In Advances in Neural Information Processing Systems, edited by H. Larochelle, M. Ranzato, R. Hadsell, M. F. Balcan, and H. Lin, 33:12472–85. Curran Associates, Inc. https://proceedings.neurips.cc/paper/2020/file/9332c513ef44b682e9347822c2e457ac-Paper.pdf.
Park, Hyesung, and Sungwook Chung. 2025. “Utilization of a Lightweight 3D u-Net Model for Reducing Execution Time of Numerical Weather Prediction Models.” Atmosphere 16 (1): 60. https://doi.org/10.3390/atmos16010060.
Saenz-Betancourt, Cristian, Dustin Draper, Victor Ocampo-Zalvide, Philipp Wernicke, Steffen Peldschus, and Fabian Duddeck. 2027. “Recurrent Neural Network Constitutive Model for Human Rib Cortical Bone and Its Biological Variability: Transitioning from Deterministic to Intrusive Stochastic Explicit FEM.” Computer Methods in Applied Mechanics and Engineering 464: 119532. https://doi.org/10.1016/j.cma.2026.119532.
Wang, Yiming, Yi Zhang, Yilun Han, Wei Xue, Tianru Chen, Yihui Zhou, Xiaohan Li, and Haishan Chen. 2026. “Global Climate Modeling with Improved Precipitation Characteristics by Learning Physics (GRIST-MPS V1.0) from Global Storm-Resolving Modeling.” Geoscientific Model Development 19 (12): 5553–70. https://doi.org/10.5194/gmd-19-5553-2026.

Appendices

Appendix: FTorch on GPU

  • Supported through native Torch GPU backends.
  • CUDA, HIP, MPS, XPU currently exposed
  • Change the device type e.g. torch_kCUDA
  • Multiple devices supported1
call torch_tensor_from_array(input_tensors(1), in_data, torch_kCUDA, torch_kCUDA device_index=2)   ! Input on CUDA:2
call torch_tensor_from_array(output_tensors(1), out_data, torch_kCPU)  ! Output on CPU

call torch_model_load(torch_net, 'path/to/saved/model.pt', torch_kCUDA device_index=2)  ! Load net on CUDA:2
call torch_model_forward(torch_net, input_tensors, output_tensors)      ! Infer

Appendix: AD in FTorch

  • Expose Torch autograd: requires_grad, torch_tensor_backward, gradient accessors
  • Overloaded operators (=,+,-,*,/,**) on torch_tensor
  • Expose optimisers (SGD, Adam, AdamW), and loss functions MSE, L1, CrossEntropy with sum and mean.
! Construct input tensors with requires_grad=.true.
! Compute some mathematical expression
call torch_tensor_from_array(Q, Q_arr, torch_kCPU)
Q = 3.0 * (a**3 - b**2)

! Reverse mode
call torch_tensor_backward(Q)
call torch_tensor_from_array(dQda, dQda_arr, torch_kCPU)
call torch_tensor_get_gradient(a, dQda)

Allows computation of loss downstream from the neural net.

Appendix: Differentiating Fortran from JAX

  • Enzyme can differentiate Fortran code from JAX — an alternative route for coupling Fortran models to ML packages, alongside FTorch/PyTorch
  • JAX calls into the Enzyme-differentiated Fortran, so gradients flow back through the model into the JAX-side ML code
  • Useful when the ML stack is already built on JAX rather than PyTorch
  • See blog post by Dion Haefner, Pasteur Labs

Appendix: LLVM IR vs MLIR

LLVM IR

  • Low-level IR of the LLVM compiler toolchain
  • Typed, SSA-form, close to the machine: pointers, alloca/load/store, basic blocks
  • Everything in LLVM (C, C++, Rust, Fortran via Flang) is lowered to this
  • What Enzyme’s pass directly operates on

MLIR

  • Multi-Level IR: a framework for defining your own IR “dialects” (tensors, loops, GPU, …) with transforms and lowering between them
  • Sits above LLVM IR; eventually lowers down to it
  • Enzyme generates MLIR for the derivative computations, then lowers that MLIR back into LLVM IR — instead of hand-writing the chain rule per operation