Reverse-mode AD through the JAX solver

Reverse-mode AD through the JAX solver#

Goal: Compute the same Manning sensitivity with jax.grad on a checkpointed loop and compare it to forward mode.

Prerequisite: Forward-mode AD

import numpy as np
import matplotlib.pyplot as plt
import jax
jax.config.update("jax_enable_x64", True)
import jax.numpy as jnp

import zoomy_core.model.boundary_conditions as BC
import zoomy_core.model.initial_conditions as IC
from zoomy_core.mesh import LSQMesh
from zoomy_core.model.models import SME
from zoomy_core.model.models.closures import ManningFriction, Newtonian, StressFree
from zoomy_core.numerics import NumericalSystemModel, ReconstructionSpec
from zoomy_core.systemmodel import SystemModel
from zoomy_jax.symsolver.solver import AdMode, SymbolicHyperbolicSolverJax
model = SME(
    level=0, dimension=2,
    closures=[Newtonian(), ManningFriction(), StressFree()],
    boundary_conditions=BC.BoundaryConditions(
        [BC.Extrapolation(tag="left"), BC.Extrapolation(tag="right")]),
)
sm = SystemModel.from_model(model)
s, P = sm.fields, sm.parameters


def initial_state(x):
    h = 1.0 + 0.2 * np.exp(-(x[0] - 5.0) ** 2)
    return {s.h: h, s.q_0: h}


sm.initial_conditions = IC.UserFunction(function=initial_state)
nsm = NumericalSystemModel.from_system_model(sm, reconstruction=ReconstructionSpec(order=1))
mesh = LSQMesh.create_1d(domain=(0.0, 10.0), n_inner_cells=100)
def objective(ad_mode, ad_checkpoints=16):
    solver = SymbolicHyperbolicSolverJax(time_end=0.5, dt=1e-2, mood=False,
                                         ad_mode=ad_mode, ad_checkpoints=ad_checkpoints)
    Q0, Qaux0 = solver.setup(mesh, nsm)
    q = s.slot(s.q_0)
    V = solver.mesh.cell_volumes[:Q0.shape[1]]

    def final_state(n):
        p = {P.n: n}
        return solver.run(Q0, solver.initial_aux(Q0, Qaux0, p), parameters=p).Q

    def J(n):
        return jnp.sum(final_state(n)[q] ** 2 * V)

    return jax.jit(J), final_state, solver


J, final_state, solver = objective(AdMode.forward)
n0 = 0.05
Q = np.asarray(final_state(n0))
J_reverse, _, _ = objective(AdMode.reverse, ad_checkpoints=16)
J_coarse, _, _ = objective(AdMode.reverse, ad_checkpoints=4)

forward = float(jax.jvp(J, (n0,), (1.0,))[1])
reverse = float(jax.grad(J_reverse)(n0))
coarse = float(jax.grad(J_coarse)(n0))
print(f"dJ/dn forward {forward:.10e}")
print(f"dJ/dn reverse {reverse:.10e}   ad_checkpoints=16")
print(f"dJ/dn reverse {coarse:.10e}   ad_checkpoints=4")
dJ/dn forward -1.0010143108e+01
dJ/dn reverse -1.0010143108e+01   ad_checkpoints=16
dJ/dn reverse -1.0010143108e+01   ad_checkpoints=4
x = mesh.cell_centers[0, :mesh.n_inner_cells]
fig, ax = plt.subplots(figsize=(6, 2.6))
ax.plot(x, Q[s.slot(s.h)], label="h")
ax.plot(x, Q[s.slot(s.q_0)], label="hu")
ax.set_xlabel("x")
ax.set_title("t = 0.5")
ax.legend()
plt.show()
../../../_images/2b9731f5d524571a89b0cc3bd723351fa6bbea30c61f6173f3dffdaf9e83f521.png
assert abs(reverse - forward) / abs(forward) < 1e-10
assert abs(coarse - reverse) / abs(reverse) < 1e-10