Gradient and sensitivity analysis of a PINN
PINN gradient_conflict.py
What is a PINN learning while it trains? Analysis callbacks watch two things: whether the loss terms pull the parameters the same way or against each other, and the spectrum of the network's neural tangent kernel, which says how evenly different patterns are learned. A units audit adds the scale conflict between terms of one residual.

Left: the cosine similarity of the two halves' loss gradients during training. Middle: the eigenvalues of the neural tangent kernel after training. Right: the trained network on the exact solution.
The problem
with the residual split into two losses, one per half of the interval. Their gradients \(\mathbf g_A\), \(\mathbf g_B\) with respect to the parameters are compared by
and the network's Jacobian \(J_{ip}=\partial u(x_i)/\partial\theta_p\) gives the tangent kernel \(K=JJ^\top\).
The jNO code
Each callback comes from a jno.callbacks factory and is handed to solve; it computes its quantity every
interval epochs from the same compiled loss. u.grad(u_net) is the parameter Jacobian of the network output:
conflict = jno.callbacks.cos_similarity(interval=100) # cosine similarity between the gradients of the loss terms
alignment = jno.callbacks.gradient_alignment(interval=100) # and the total alignment of all of them
ntk = jno.callbacks.ntk_spectrum(u.grad(u_net), n_points=512, top_k=10, interval=500) # K = J Jᵀ of the network
crux = jno.core([pde(xl).mse, pde(xr).mse])
crux.solve(5000, log=1000, callbacks=[conflict, alignment, ntk])
jno.units audits a residual before training. On a thin domain, \(L_x=1\) and \(L_y=1/20\), the two terms of
\(u_{xx}+u_{yy}\) differ by \((L_x/L_y)^2=400\); jno.units.nondimensionalize reports it and jno.units.rescale rewrites
the residual into its \(O(1)\) form:
# Scale conflict, the twin: the terms of ONE residual on a thin domain (Lx = 1, Ly = 1/20) differ by (Lx/Ly)².
Lx, Ly, U = 1.0, 0.05, 3.0
ad = jno.shape.rect(0.0, 0.0, Lx, Ly, size=0.1).domain()
ax, ay, _ = ad.variable("interior", split=True)
ax, ay = ax.unit("m").scale(Lx), ay.unit("m").scale(Ly) # characteristic lengths
au = jno.nn(foundax.mlp(in_features=2, hidden_dims=8, num_layers=2, key=jax.random.PRNGKey(1)))(ax, ay)
au = au.unit("K").scale(U).scalar.bind(x=ax, y=ay) # and a characteristic temperature
aniso = au.xx + au.yy
assert not jno.units.check(aniso).warnings # both terms are K·m⁻²
terms = jno.units.nondimensionalize(aniso).residuals[0].terms
scale_sep = terms[1].pi / terms[0].pi
print(f"scale separation = {scale_sep:.0f}× (= (Lx/Ly)² = {(Lx / Ly) ** 2:.0f})")
assert abs(scale_sep - (Lx / Ly) ** 2) < 1e-6
transformed, rescaler = jno.units.rescale(aniso) # the residual in O(1) form, and the map back to physical units
assert rescaler.field_scale == U
assert float(rescaler.to_physical(1.0)) == U
Result
| quantity | value |
|---|---|
| trained network against \(u^\*\), 5000 epochs | rel. \(L^2\) \(3.8\times10^{-5}\) |
| cosine similarity: untrained / after 100 epochs | 0.8 / −0.94 |
| NTK at epoch 4500: \(\lambda_{\max}\), effective rank | 111, 1.06 |
| scale ratio of \(u_{xx}\) and \(u_{yy}\) on the thin domain | 400 |
The two halves are parts of one loss, so near the minimum their gradients must cancel and the similarity tends to \(-1\). An effective rank near 1 means a single mode dominates learning while the rest are almost frozen.
Full script
The whole script, as it runs in the tests
"""Gradient and sensitivity analysis of a PINN with jno.callbacks: gradient conflict, neural tangent kernel, scale."""
import foundax
import jax
import numpy as np
import optax
import jno
run = jno.setup(__file__)
π, sin = jno.np.pi, jno.np.sin
d = jno.Path(0.0, 0.0).line_to(1.0, 0.0).curve(size=0.001).domain()
x, _ = d.variable("interior")
xl, _ = d.variable("left", where=lambda x: x < 0.5) # the two halves of the domain, as two loss terms
xr, _ = d.variable("right", where=lambda x: x >= 0.5)
u_exact = sin(π * x) / π**2 # for the check only, not used in training
u_net = jno.nn(foundax.mlp(in_features=1, hidden_dims=32, num_layers=3, key=jax.random.PRNGKey(0)))
u_net.optimizer(optax.adam(1e-3))
field = lambda x: (u_net(x) * x * (1 - x)).scalar.bind(x=x) # hard u(0) = u(1) = 0
u = field(x)
pde = lambda x: -field(x).xx - sin(π * x) # -u'' = sin(πx)
conflict = jno.callbacks.cos_similarity(interval=100) # cosine similarity between the gradients of the loss terms
alignment = jno.callbacks.gradient_alignment(interval=100) # and the total alignment of all of them
ntk = jno.callbacks.ntk_spectrum(u.grad(u_net), n_points=512, top_k=10, interval=500) # K = J Jᵀ of the network
crux = jno.core([pde(xl).mse, pde(xr).mse])
crux.solve(5000, log=1000, callbacks=[conflict, alignment, ntk])
u_h, u_ref = crux.eval([u, u_exact])
rel_l2 = float(np.linalg.norm(u_h - u_ref) / np.linalg.norm(u_ref))
print(f"Relative L² error: {rel_l2:.3e}")
assert rel_l2 < 1e-1, f"solution error too large: {rel_l2:.3e}"
cos_track = conflict.result["cos_sim_matrix"][:, 0, 1] # left gradient vs right gradient, every 100 epochs
cos_sim = float(cos_track[-1])
print(f"cos_sim (left vs right gradient) = {cos_sim:.4f}, total alignment = {alignment.result['alignment'][-1]:.4f}")
assert -1.0 <= cos_sim <= 1.0
eigs = np.sort(ntk.result["all_eigvals"][-1])[::-1].clip(0) # the NTK spectrum at the last sample
eff_rank = float(eigs.sum() ** 2 / ((eigs**2).sum() + 1e-12)) # participation ratio
cond = float(ntk.result["condition_number"][-1])
print(
f"NTK {eigs.size}×{eigs.size}: λ_max = {eigs[0]:.4f}, λ_min = {eigs[-1]:.4f}, eff. rank = {eff_rank:.2f}, cond = {cond:.1e}"
)
# Scale conflict, the twin: the terms of ONE residual on a thin domain (Lx = 1, Ly = 1/20) differ by (Lx/Ly)².
Lx, Ly, U = 1.0, 0.05, 3.0
ad = jno.shape.rect(0.0, 0.0, Lx, Ly, size=0.1).domain()
ax, ay, _ = ad.variable("interior", split=True)
ax, ay = ax.unit("m").scale(Lx), ay.unit("m").scale(Ly) # characteristic lengths
au = jno.nn(foundax.mlp(in_features=2, hidden_dims=8, num_layers=2, key=jax.random.PRNGKey(1)))(ax, ay)
au = au.unit("K").scale(U).scalar.bind(x=ax, y=ay) # and a characteristic temperature
aniso = au.xx + au.yy
assert not jno.units.check(aniso).warnings # both terms are K·m⁻²
terms = jno.units.nondimensionalize(aniso).residuals[0].terms
scale_sep = terms[1].pi / terms[0].pi
print(f"scale separation = {scale_sep:.0f}× (= (Lx/Ly)² = {(Lx / Ly) ** 2:.0f})")
assert abs(scale_sep - (Lx / Ly) ** 2) < 1e-6
transformed, rescaler = jno.units.rescale(aniso) # the residual in O(1) form, and the map back to physical units
assert rescaler.field_scale == U
assert float(rescaler.to_physical(1.0)) == U