← Back to Pull requests

[Enzyme-JAX] Add Fortran support via fortran_call #3821

Open
unknown opened this pull request with 430 lines diff across 5 files
View on GitHub
unknown unknown commented on Nov 03, 2026 21:07 UTC
Author

Overview

This PR adds native Fortran support to Enzyme-JAX via a new fortran_call API, enabling direct execution, JIT compilation, and automatic differentiation (forward-mode JVP, reverse-mode VJP/grad) of Fortran routines in JAX.

Key Changes

1. In-Process Flang Compilation (flang_compile.h, flang_compile.cc):
- Compiles Fortran source code directly to LLVM IR in-memory using LLVM Flang (Fortran::frontend::CompilerInstance, CompilerInvocation).
- Runs Flang's MLIR FIR-to-LLVM lowering pipeline (createMLIRToLLVMPassPipeline).
- Bootstraps standard intrinsic module headers (iso_c_binding, iso_fortran_env, ieee_arithmetic, etc.) from an in-memory virtual filesystem.
- Inspects FIR function signatures to extract parameter kinds (raw pointers, value arguments, box/descriptors), shapes, element types, and intent.
- Demangles lowered symbol names (e.g. FIR _QPfoo to foo_) to match LLVM IR export definitions.

2. Fortran ABI & Calling Convention Adapter (clang_compile.cc):
- Synthesizes an inline C++ wrapper conforming to Enzyme's call contract:
- Directly passes scalars by-value when marked with VALUE.
- Passes raw pointers (void*) for standard dummy arrays/scalars.
- Constructs standard ISO Fortran CFI_cdesc_t descriptors for assumed-shape arrays, allocatables, and pointer dummy arguments.
- Reverses array dimensions and byte strides so JAX row-major C-contiguous memory maps directly to Fortran column-major layout with zero memory copy.
- Wraps non-differentiable integers and booleans with enzyme_const so Enzyme AD focuses strictly on differentiable floating-point tensors.

3. Static Flang Runtime Linking (enzyme_call.cc, BUILD):
- Embeds static @llvm-project//flang-rt:runtime into enzyme_call via flang_rt_archive.inc.
- Registers an LLJIT StaticLibraryDefinitionGenerator with the archive so all standard Fortran runtime routines (I/O, descriptors, math intrinsics) resolve seamlessly inside the JIT execution session.

4. Python Frontend & AD Integration (primitives.py, __init__.py):
- Exports fortran_call from enzyme_ad.jax.
- Supports subroutines (multiple outputs) and scalar-returning functions.
- Enhances enzyme_jvp and enzyme_vjp to handle non-differentiable outputs (float0 / ad.Zero) and multiple outputs cleanly.

5. Comprehensive Test Suite (test/fortran_test.py, test/BUILD):
- Tests pure scalar functions (VALUE and reference arguments).
- Tests vector and matrix operations (scale, add, GEMV/GEMM).
- Tests assumed-shape arrays using Fortran 90 modules and array descriptors.
- Tests subroutines with multiple return arrays and non-differentiable configuration inputs (dimensions, scaling factors).
- Tests both forward-mode (jax.jvp) and reverse-mode (jax.grad / jax.vjp) automatic differentiation with numerical finite difference validation.
- Tests integration with jax.jit.

Verification

  • Bazel tests pass:

  •   bazel test --config=public_cache --repo_env=CC=/usr/bin/clang-18 --test_env=JAX_PLATFORMS=cpu --test_output=errors //test:fortran_test //test:test //test:testffi
      

    - //test:fortran_test: PASSED
    - //test:test: PASSED
    - //test:testffi: PASSED
  • buildifier checked and clean.

  • git clang-format clean on all touched lines.

  • ASCII encoding clean (ord(c) < 128 on all files).
  • Diff: 430 lines (+322 / -108) across 5 files Reviewer: joewallwork Review duration: 28997m
    All Vouch review confidence checks passed
    Residual risk 0.24 = Change Risk (0.45) × (1 − Review Confidence (0.47)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.45 · 430 lines diff across 5 files
    0.45
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    46%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.363
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #3821"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 46.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 45.1% (MEDIUM) · Higher = larger blast radius
    45.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 46.7% · Lower = rushed or shallow review
    46.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 24.1% · Safe to merge
    24.1%