Physics-informed neural networks II: failure modes and remedies
Study PINN failure modes including gradient imbalance, spectral bias and temporal causality, and evaluate adaptive weighting, Fourier features, causal training and residual-based sampling.
After this lesson you can
- Diagnose gradient imbalance between loss terms and apply adaptive weighting based on gradient norms or NTK.
- Explain spectral bias with the neural tangent kernel and mitigate it with Fourier embeddings.
- Implement causal training with temporal weights and check error propagation in evolution problems.
- Apply residual-guided adaptive sampling of collocation points.
- Critically read a PINN paper, evaluating references, metrics and comparisons with classical solvers.
Before you start
- 29Physics-informed neural networkResidual loss and collocationPINNs versus classical solversAdaptive mesh refinementSpectral convergencePredictability horizon
- 15Vanishing gradientsExploding gradients
- 13Generalization in the kernel regimeSpectral bias
- 06Gradient descent dynamics on quadraticsCondition number of a functionLinear convergence of gradient descent for strongly convex functions
- 24Fourier features for coordinate networks
Small loss can hide failure
In the previous lesson a PINN approximated a smooth Burgers wave. Now change the question: what happens when one term dominates the gradient, the solution has difficult frequencies or the optimizer fits late times before respecting the initial condition? A total-loss curve does not distinguish these cases.
For periodic convection , any constant satisfies the interior equation. If residual loss dominates and the initial condition has little weight, a constant may seem attractive to the optimizer even though it is not the requested solution. This is a possibility to diagnose, not a theorem forcing every PINN to converge to zero.
In figure 3 of Krishnapriyan and colleagues, relative error of their convection PINN moves from for to for in the particular study configurations. The authors analyze the loss landscape and test progressive training. This is evidence of a failure mode under those protocols, not a bound for arbitrary architectures, scales or optimizers.
Diagnose before changing
PINN failure modes can manifest differently: the equation fits collocation points but not between them; residual falls while the boundary stays wrong; or the initial condition is satisfied and the solution degrades as time advances. Record each loss term, error on independent data, out-of-sample residual and gradient norms by term and layer. For evolution, also break down error by physical time.
Do not confuse small residual with small error without a stability estimate connecting them. Collocation residual is a finite sum, and the equation may admit multiple solutions if boundary or initial data are missing. Compare with a reference of verified resolution and check its convergence before attributing error to the network.
Gradient imbalance
For , the update depends on . Loss values alone do not determine gradient norms. A small term can dominate the step, and two large gradients can point in opposite directions. Wang, Teng and Perdikaris studied these pathologies and proposed adapting weights with gradient statistics.
Adaptive loss weighting tries to balance contributions. An illustrative scheme calculates and , and smoothly updates toward . It is wise to bound the ratio and use a moving average, since may be nearly zero. Choice of norm, weights, update frequency and observed layers changes the algorithm; equalizing norms does not guarantee minimizing error or resolving directional conflict.
The figure comes from a run for , 32 fixed interior points and a 32-32 tanh MLP. With seed 25 and 700 Adam steps, relative error on a grid of 201 points was approximately with fixed weights and with the adaptive scheme of that run. The adaptive weight reaches its limit of 1000: do not conclude distributions always equalize or that this bound is optimal. The histogram uses absolute values and hides signs: it cannot by itself measure the angle between the two gradients. The evaluation grid shares endpoints with training and is a synthetic check, not an external benchmark.
Tangent kernel and learning speeds
Spectral bias and the neural tangent kernel explain an idealized case. Let be the vector of output or residual errors evaluated at fixed points. Linearize around : with constant . For loss and gradient flow ,
is symmetric positive semidefinite because . If , then
Here is optimization time, not physical time. A component with small decays slowly and a component in the kernel of does not change in this model. The identity is exact for the linearized model and fixed ; a finite network can change its kernel during training. With weighted losses, speeds depend on the weighted matrix, not just eigenvalues of individual blocks.
Wang, Yu and Perdikaris analyze boundary and residual blocks of PINN NTKs and show their scales can differ. In their Poisson example those blocks’ eigenvalues have different orders of magnitude. It does not follow that every high frequency is always slow: the differential operator, point distribution and architecture change the kernel and correspondence between eigenvectors and frequencies.
Fourier features replace with pairs and before the MLP. Tancik and colleagues study how this transformation changes the effective kernel and bandwidth in low-dimensional regression. Changing the scale of changes accessible frequencies; it does not guarantee that every PINN spectrum flattens or that an arbitrarily high frequency generalizes between points.
The network fits at 32 points with seed 25. In one run, relative error on a 201-point grid after 1000 steps was without Fourier features and at scale 4. The latter includes precisely sines and cosines of frequency , so the example shows the importance of a suitable representation, not a universal advantage. The NTK is calculated at initialization using ; eigenvectors have arbitrary sign and the kernel may change afterward.
Causality and physical time
Divide the physical interval into ordered blocks with residual losses . A causal training scheme uses
With , weights are nonincreasing for a fixed evaluation. They are usually treated as constants when differentiating the objective: allowing gradients through them can let the optimizer reduce the weight of later times by increasing earlier losses. Blocks and initial weight must be defined together with treatment of the initial condition; too large an can leave late blocks with almost no gradient. A different alternative is to train successive time windows and pass on their initial state, taking care with error accumulation.
In the Allen–Cahn case of Wang, Sankaran and Perdikaris, table 1 reports relative error for the original formulation and for their causal MLP. Their figure and description indicate and iterations respectively; these are not equal-step comparisons. Their reference uses a spectral discretization and a time integrator described in the appendix. These are published figures for that problem, not results of the lab you will build here.
By default, the figure uses , five blocks and seed 25. In that short run, after 1500 steps spatial RMSE at was approximately for standard training and for causal. Both are poor for this case, and the causal variant did not correct error propagation in that configuration. The second case uses and 32 blocks: its error falls, although the standard one finishes better. These are reproducible diagnostics of specific configurations, not a refutation of published results; changing representation, budget or weights requires another ablation.
Where to place points and how to divide the domain
Residual-adaptive sampling proposes candidates, evaluates and adds or resamples points where it is large. An independent test must still cover the entire domain: examining only points just added does not reveal what happens elsewhere. Changing the point distribution also changes the measure approximated by the loss; estimating the same integral under nonuniform sampling requires importance weights and sufficient support.
Domain decomposition assigns approximators to subdomains or windows. It may relieve local scales, but introduces interface conditions: at least solution continuity and, when the model requires it, flux continuity. A physical discontinuity requires an appropriate formulation rather than indiscriminately imposing smoothness. More subdomains also add costs and coupling decisions.
Before changing optimizers, scale variables and equations with consistent units: a poorly conditioned transformation can produce derivatives of very different magnitudes. Adam and L-BFGS solve different optimization problems in practice; the latter approximates curvature information using a history and often needs multiple evaluations of one loss during line search. If points are resampled within that search, the objective changes between evaluations and the curvature interpretation weakens. Freeze points during each search, measure the cost of all evaluations and check out-of-sample error. Neither method guarantees reaching the physical solution.
Reproducible laboratories
The next three cells reconstruct the figure experiments from scratch. They do not read captures or report files: points, architecture, seeds and objectives are in the code. Choose CPU or CUDA according to availability. Observed numbers correspond to one run and can vary by device or version; they are not a complete replication of the papers’ budgets.
Poisson gradients
The manufactured equation is with zero Dirichlet at . Boundary loss is the mean of squared values at both endpoints. The weight is updated with a moving average and capped at 1000; histograms use of absolute gradients of each matrix, including the boundary term’s weight.
"""Datos reales del desequilibrio de gradientes en Poisson 1D manufacturado."""
import json
from pathlib import Path
import numpy as np
import torch
from torch import nn
torch.set_num_threads(1)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
dtype = torch.float64
omega = 4 * torch.pi
edges = np.linspace(-12, 8, 41)
history = []
for adaptive in (False, True):
torch.manual_seed(25)
model = nn.Sequential(nn.Linear(1,32), nn.Tanh(), nn.Linear(32,32), nn.Tanh(), nn.Linear(32,1)).to(device=device,dtype=dtype)
params = list(model.parameters())
weights = [(name, param) for name, param in model.named_parameters() if name.endswith('weight')]
opt = torch.optim.Adam(params, lr=0.002)
x = torch.linspace(0,1,34,device=device,dtype=dtype)[1:-1,None]
boundary = torch.tensor([[0.],[1.]],device=device,dtype=dtype)
test = torch.linspace(0,1,201,device=device,dtype=dtype)[:,None]
truth = torch.sin(omega*test)
lam = 1.0
snapshots = []
for step in range(701):
z = x.detach().clone().requires_grad_(True)
u = model(z)
du = torch.autograd.grad(u,z,torch.ones_like(u),create_graph=True)[0]
ddu = torch.autograd.grad(du,z,torch.ones_like(du),create_graph=True)[0]
lr = (ddu + omega**2*torch.sin(omega*z)).square().mean()
lb = model(boundary).square().mean()
if adaptive or step in (0,100,350,700):
gr = torch.autograd.grad(lr,params,retain_graph=True,allow_unused=True)
gb = torch.autograd.grad(lb,params,retain_graph=True,allow_unused=True)
nr = torch.sqrt(sum((g.square().sum() for g in gr if g is not None))).item()
nb = torch.sqrt(sum((g.square().sum() for g in gb if g is not None))).item()
if adaptive:
target = min(1000.,max(0.001,nr/(nb+1e-12)))
lam = 0.9*lam+0.1*target
if step in (0,100,350,700):
layer_hist = []
for name, param in weights:
ix = next(i for i,p in enumerate(params) if p is param)
def bins(g, factor):
a = np.abs(g.detach().cpu().numpy().ravel()*factor)
return np.histogram(np.log10(np.maximum(a,1e-12)),bins=edges)[0].tolist()
layer_hist.append({'name':name, 'residual':bins(gr[ix],1), 'boundary':bins(gb[ix],lam)})
with torch.no_grad():
err = (torch.linalg.vector_norm(model(test)-truth)/torch.linalg.vector_norm(truth)).item()
snapshots.append({'step':step,'weight':lam,'residual_loss':lr.item(),'boundary_loss':lb.item(),
'gradient_residual_norm':nr,'gradient_boundary_norm':nb,'relative_l2':err,'layers':layer_hist})
if step < 700:
opt.zero_grad(set_to_none=True)
(lr+lam*lb).backward()
opt.step()
history.append({'adaptive':adaptive,'snapshots':snapshots})
out = {'seed':25,'device':str(device),'omega':float(omega),'bins':edges.tolist(),'runs':history,
'notes':'Poisson u=sin(4πx), 32 puntos interiores, red tanh 32-32, 700 pasos Adam; histograma log10 del valor absoluto por capa; término de contorno ya multiplicado por su peso.'}
print([(r['adaptive'], [(s['step'],s['relative_l2'],s['boundary_loss'],s['weight']) for s in r['snapshots']]) for r in history])npm run lab and open the connection link.Tangent kernel and high-frequency regression
The following control explicitly calculates the Jacobian of 32 outputs with respect to all parameters and diagonalizes . It then trains on the sinusoid. Changing the input from one to two components also changes parametrization: do not interpret the eigenvalue ratio as an isolated causal comparison of one variable.
"""NTK empírica inicial y regresión de una senoide para cuatro arquitecturas."""
import json
from pathlib import Path
import numpy as np
import torch
from torch import nn
torch.set_num_threads(1)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
dtype = torch.float64
n = 32
x = torch.linspace(0,1,n,device=device,dtype=dtype)[:,None]
test = torch.linspace(0,1,201,device=device,dtype=dtype)[:,None]
truth = torch.sin(8*torch.pi*test)
result = []
for sigma in (0.,1.,2.,4.):
torch.manual_seed(25)
input_dim = 1 if sigma == 0 else 2
model = nn.Sequential(nn.Linear(input_dim,64),nn.Tanh(),nn.Linear(64,1)).to(device=device,dtype=dtype)
def features(z):
return z if sigma == 0 else torch.cat([torch.sin(2*torch.pi*sigma*z),torch.cos(2*torch.pi*sigma*z)],dim=1)
params = list(model.parameters())
rows = []
for i in range(n):
y = model(features(x[i:i+1]))
gradients = torch.autograd.grad(y,params)
rows.append(torch.cat([g.reshape(-1) for g in gradients]).detach())
J = torch.stack(rows)
K = (J @ J.T / n).cpu().numpy()
eigenvalues, vectors = np.linalg.eigh(K)
order = np.argsort(eigenvalues)[::-1]
eigenvalues, vectors = eigenvalues[order], vectors[:,order]
# Fijar signo solo para que los vectores sean comparables entre ejecuciones.
for j in range(3):
if vectors[np.argmax(np.abs(vectors[:,j])),j] < 0:
vectors[:,j] *= -1
opt = torch.optim.Adam(params,lr=0.002)
y_train = torch.sin(8*torch.pi*x)
snapshots = []
for step in range(1001):
if step in (0,100,500,1000):
with torch.no_grad():
pred = model(features(test))
error = torch.linalg.vector_norm(pred-truth)/torch.linalg.vector_norm(truth)
snapshots.append({'step':step,'relative_l2':error.item(),'prediction':pred.flatten().cpu().tolist()})
if step < 1000:
opt.zero_grad(set_to_none=True)
(model(features(x))-y_train).square().mean().backward()
opt.step()
result.append({'sigma':sigma,'eigenvalues':eigenvalues.tolist(),
'eigenvectors':vectors[:,:3].T.tolist(),'snapshots':snapshots})
out = {'seed':25,'device':str(device),'x_train':x.flatten().cpu().tolist(),
'x_test':test.flatten().cpu().tolist(),'truth':truth.flatten().cpu().tolist(),'runs':result,
'notes':'Regresión directa, no PINN; NTK empírica inicial JJᵀ/32. Fourier fija sin y cos de 2πσx. Adam 1000 pasos.'}
print([(r['sigma'],[(s['step'],s['relative_l2']) for s in r['snapshots']]) for r in result])npm run lab and open the connection link.Convection and causal weights
Both networks receive the same initialization and points. Periodic input imposes spatial periodicity by construction; residual is divided by without changing its zeros. Initial loss is retained in both and causal weights are detached from the graph. RMSE by time is evaluated at spatial positions shifted relative to collocation.
"""Convección periódica: dos entrenamientos y errores por tiempo físico."""
import json
import time
import os
from pathlib import Path
import numpy as np
import torch
from torch import nn
torch.set_num_threads(1)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
dtype = torch.float64
beta, epsilon, steps_max = 5., 1., 1500
slabs = 5
x = (torch.arange(32,device=device,dtype=dtype)+0.5)/32
t = (torch.arange(slabs,device=device,dtype=dtype)+0.5)/slabs
T,X = torch.meshgrid(t,x,indexing='ij')
coords = torch.stack([X.reshape(-1),T.reshape(-1)],dim=1)
initial = torch.stack([x,torch.zeros_like(x)],dim=1)
test_x = (torch.arange(64,device=device,dtype=dtype)+0.5)/64
test_t = torch.linspace(0,1,21,device=device,dtype=dtype)
TT,XX = torch.meshgrid(test_t,test_x,indexing='ij')
test = torch.stack([XX.reshape(-1),TT.reshape(-1)],dim=1)
truth = torch.sin(2*torch.pi*(XX-beta*TT))
def features(z):
return torch.cat([torch.sin(2*torch.pi*z[:,:1]),torch.cos(2*torch.pi*z[:,:1]),z[:,1:2]],dim=1)
runs = []
for causal in (False, True):
started=time.perf_counter()
torch.manual_seed(25)
model=nn.Sequential(nn.Linear(3,32),nn.Tanh(),nn.Linear(32,32),nn.Tanh(),nn.Linear(32,1)).to(device=device,dtype=dtype)
optimizer=torch.optim.Adam(model.parameters(),lr=0.002)
snapshots=[]
for step in range(steps_max+1):
z=coords.detach().clone().requires_grad_(True)
u=model(features(z))
grad=torch.autograd.grad(u,z,torch.ones_like(u),create_graph=True)[0]
residual=(grad[:,1:2]+beta*grad[:,:1]) / np.sqrt(1+beta**2)
losses=residual.square().reshape(slabs,-1).mean(dim=1)
weights=torch.exp(-epsilon*torch.cat([torch.zeros(1,device=device,dtype=dtype),torch.cumsum(losses.detach()[:-1],dim=0)])) if causal else torch.ones_like(losses)
init_loss=(model(features(initial))-torch.sin(2*torch.pi*initial[:,:1])).square().mean()
loss=(weights*losses).mean()+5*init_loss
if step in (0,100,500,steps_max):
with torch.no_grad():
prediction=model(features(test)).reshape(21,64)
error=(prediction-truth).square().mean(dim=1).sqrt()
snapshots.append({'step':step,'weights':weights.detach().cpu().tolist(),
'losses':losses.detach().cpu().tolist(),'initial_loss':init_loss.item(),
'rmse_by_time':error.cpu().tolist()})
if step < steps_max:
optimizer.zero_grad(set_to_none=True)
loss.backward()
optimizer.step()
runs.append({'causal':causal,'snapshots':snapshots,'seconds':time.perf_counter()-started})
out={'seed':25,'device':str(device),'beta':beta,'epsilon':epsilon,'times':test_t.cpu().tolist(),
'slab_times':t.cpu().tolist(),'runs':runs,
'notes':f'Convección periódica manufacturada u=sin(2π(x−βt)); residuo dividido por √(1+β²); 5 bloques, 32 puntos por bloque; Adam {steps_max} pasos, misma inicialización; pesos detenidos.'}
print([(r['causal'],r['seconds'],[(s['step'],s['rmse_by_time'][-1]) for s in r['snapshots']]) for r in runs])npm run lab and open the connection link.A causal case that does reduce error
Repeat with milder convection , 32 time blocks, and 3000 steps. The reference remains analytical solution and both models use the same architecture, seed and points. In the documented run, maximum spatial RMSE over 21 times fell from 0.819 initially to 0.0451 with causal weights. The standard variant’s final error was 0.0164: it also solved the case reasonably and did better at this budget. Causal error did not decrease monotonically; at 500 steps its maximum exceeded 1.8. Thus we verify absolute improvement under this configuration without attributing it exclusively to causality. Both and block count differ from the earlier figure, so those two trials do not isolate temporal-resolution effects.
"""Convección periódica: dos entrenamientos y errores por tiempo físico."""
import json
import os
from pathlib import Path
import numpy as np
import torch
from torch import nn
torch.set_num_threads(1)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
dtype = torch.float64
beta, epsilon, steps_max = 1., 5., 3000
slabs = 32
x = (torch.arange(32,device=device,dtype=dtype)+0.5)/32
t = (torch.arange(slabs,device=device,dtype=dtype)+0.5)/slabs
T,X = torch.meshgrid(t,x,indexing='ij')
coords = torch.stack([X.reshape(-1),T.reshape(-1)],dim=1)
initial = torch.stack([x,torch.zeros_like(x)],dim=1)
test_x = (torch.arange(64,device=device,dtype=dtype)+0.5)/64
test_t = torch.linspace(0,1,21,device=device,dtype=dtype)
TT,XX = torch.meshgrid(test_t,test_x,indexing='ij')
test = torch.stack([XX.reshape(-1),TT.reshape(-1)],dim=1)
truth = torch.sin(2*torch.pi*(XX-beta*TT))
def features(z):
return torch.cat([torch.sin(2*torch.pi*z[:,:1]),torch.cos(2*torch.pi*z[:,:1]),z[:,1:2]],dim=1)
runs = []
for causal in (False, True):
torch.manual_seed(25)
model=nn.Sequential(nn.Linear(3,32),nn.Tanh(),nn.Linear(32,32),nn.Tanh(),nn.Linear(32,1)).to(device=device,dtype=dtype)
optimizer=torch.optim.Adam(model.parameters(),lr=0.002)
snapshots=[]
for step in range(steps_max+1):
z=coords.detach().clone().requires_grad_(True)
u=model(features(z))
grad=torch.autograd.grad(u,z,torch.ones_like(u),create_graph=True)[0]
residual=(grad[:,1:2]+beta*grad[:,:1]) / np.sqrt(1+beta**2)
losses=residual.square().reshape(slabs,-1).mean(dim=1)
weights=torch.exp(-epsilon*torch.cat([torch.zeros(1,device=device,dtype=dtype),torch.cumsum(losses.detach()[:-1],dim=0)])) if causal else torch.ones_like(losses)
init_loss=(model(features(initial))-torch.sin(2*torch.pi*initial[:,:1])).square().mean()
loss=(weights*losses).mean()+5*init_loss
if step in (0,100,500,steps_max):
with torch.no_grad():
prediction=model(features(test)).reshape(21,64)
error=(prediction-truth).square().mean(dim=1).sqrt()
snapshots.append({'step':step,'weights':weights.detach().cpu().tolist(),
'losses':losses.detach().cpu().tolist(),'initial_loss':init_loss.item(),
'rmse_by_time':error.cpu().tolist()})
if step < steps_max:
optimizer.zero_grad(set_to_none=True)
loss.backward()
optimizer.step()
runs.append({'causal':causal,'snapshots':snapshots})
out={'seed':25,'device':str(device),'beta':beta,'epsilon':epsilon,'times':test_t.cpu().tolist(),
'slab_times':t.cpu().tolist(),'runs':runs,
'notes':f'Convección periódica manufacturada u=sin(2π(x−βt)); residuo dividido por √(1+β²); 32 bloques, 32 puntos por bloque; Adam {steps_max} pasos, misma inicialización; pesos detenidos.'}
print([(r['causal'], [(s['step'],max(s['rmse_by_time']),s['rmse_by_time'][-1]) for s in r['snapshots']]) for r in runs])npm run lab and open the connection link.Periodic Allen–Cahn: also compare when there is no improvement
We solve on , with and periodic boundary. The reference uses Fourier derivatives and DOP853; doubling from 128 to 256 points gives relative difference 0.000465 on the common grid. This checks spatial refinement in this comparison, not exact total error. Use the 256-point solution as reference and evaluate on the 128 common points and 21 times.
With the same seed 25, architecture and 2000 Adam steps, space-time relative error was 0.8782 standard and 0.8564 causal. Both are large: this short run does not reproduce the paper’s budget and does not prove the strategy solved the problem. Weights use losses detached from the gradient and . Repeat across seeds and budgets before drawing conclusions.
"""Allen-Cahn periódico, referencia espectral refinada y PINN corta de control."""
import json
import time
from pathlib import Path
import numpy as np
from scipy.integrate import solve_ivp
import torch
from torch import nn
times = np.linspace(0,1,21)
def reference(n):
x = -1 + 2*np.arange(n)/n
k = 2*np.pi*np.fft.fftfreq(n,d=2/n)
initial = x*x*np.cos(np.pi*x)
def rhs(t,u):
uxx = np.fft.ifft(-(k*k)*np.fft.fft(u)).real
return 0.0001*uxx+5*u-5*u**3
result = solve_ivp(rhs,(0,1),initial,t_eval=times,method='DOP853',rtol=1e-9,atol=1e-10,max_step=.005)
if not result.success:
raise RuntimeError(result.message)
return x,result.y.T
x128,ref128 = reference(128)
ref_started=time.perf_counter()
x256,ref256 = reference(256)
reference_seconds=time.perf_counter()-ref_started
coarse_fine = np.linalg.norm(ref128-ref256[:,::2])/np.linalg.norm(ref256[:,::2])
print('diferencia referencia 128/256',coarse_fine,flush=True)
torch.set_num_threads(1)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
dtype=torch.float64
slabs,epsilon,steps=5,10.,2000
xtrain=-1+2*(torch.arange(48,device=device,dtype=dtype)+0.5)/48
ttrain=(torch.arange(slabs,device=device,dtype=dtype)+0.5)/slabs
T,X=torch.meshgrid(ttrain,xtrain,indexing='ij')
coords=torch.stack([X.reshape(-1),T.reshape(-1)],dim=1)
initial=torch.stack([xtrain,torch.zeros_like(xtrain)],dim=1)
test_x=torch.tensor(x128,device=device,dtype=dtype)
test_t=torch.tensor(times,device=device,dtype=dtype)
TT,XX=torch.meshgrid(test_t,test_x,indexing='ij')
test=torch.stack([XX.reshape(-1),TT.reshape(-1)],dim=1)
truth=torch.tensor(ref256[:,::2],device=device,dtype=dtype)
def features(z):
return torch.cat([torch.sin(torch.pi*z[:,:1]),torch.cos(torch.pi*z[:,:1]),z[:,1:2]],dim=1)
runs=[]
for causal in (False,True):
started=time.perf_counter()
torch.manual_seed(25)
model=nn.Sequential(nn.Linear(3,32),nn.Tanh(),nn.Linear(32,32),nn.Tanh(),nn.Linear(32,1)).to(device=device,dtype=dtype)
optimizer=torch.optim.Adam(model.parameters(),lr=0.002)
snapshots=[]
for step in range(steps+1):
z=coords.detach().clone().requires_grad_(True)
u=model(features(z))
grad=torch.autograd.grad(u,z,torch.ones_like(u),create_graph=True)[0]
uxx=torch.autograd.grad(grad[:,:1],z,torch.ones_like(grad[:,:1]),create_graph=True)[0][:,:1]
residual=grad[:,1:2]-0.0001*uxx+5*u**3-5*u
losses=residual.square().reshape(slabs,-1).mean(dim=1)
weights=torch.exp(-epsilon*torch.cat([torch.zeros(1,device=device,dtype=dtype),torch.cumsum(losses.detach()[:-1],dim=0)])) if causal else torch.ones_like(losses)
init_loss=(model(features(initial))-initial[:,:1]**2*torch.cos(torch.pi*initial[:,:1])).square().mean()
loss=(weights*losses).mean()+100*init_loss
if step in (0,100,500,steps):
with torch.no_grad():
prediction=model(features(test)).reshape(len(times),len(x128))
relative=(torch.linalg.vector_norm(prediction-truth)/torch.linalg.vector_norm(truth)).item()
rmse=(prediction-truth).square().mean(dim=1).sqrt().cpu().tolist()
snapshots.append({'step':step,'relative_l2':relative,'rmse_by_time':rmse,'weights':weights.detach().cpu().tolist()})
if step<steps:
optimizer.zero_grad(set_to_none=True)
loss.backward()
optimizer.step()
runs.append({'causal':causal,'snapshots':snapshots,'seconds':time.perf_counter()-started})
out={'seed':25,'device':str(device),'epsilon':epsilon,'reference_difference':coarse_fine,
'reference_seconds':reference_seconds, 'times':times.tolist(),'slab_times':ttrain.cpu().tolist(),'runs':runs,
'notes':'Allen-Cahn periódico, referencia Fourier 128/256 y DOP853; control corto Adam 2000 pasos, no réplica del presupuesto publicado.'}
print('tiempo referencia 256',reference_seconds)
print([(r['causal'],r['seconds'],r['snapshots'][-1]['relative_l2']) for r in runs])npm run lab and open the connection link.Helmholtz: ablation and spectral reference
On impose , , and manufacture . The value avoids resonant Dirichlet eigenvalues. The reference diagonalizes the operator in a sine basis; with 127 interior points its relative error against the exact solution was 1.2e-15. Networks are evaluated on that same grid, distinct from collocation. Fourier deliberately includes the solution frequency; adaptive sampling retains 32 anchors and adds 32 highest-residual points every 100 steps. This is not a blind comparison or universal rule.
One run, seed 25, cuda device, 1500 Adam steps:
| Method | Relative error | Measured time (s) |
|---|---|---|
| Spectral | 1.2e-15 | 0.0004459 |
| Uniform | 1.0001 | 19.48 |
| Fourier | 0.00963 | 22.10 |
| Adaptive | 1.0001 | 20.17 |
Times are from one run in this environment, include different work and do not prove a general speed relation; the spectral method directly solves a known linear problem, while networks are trained. Boundary is penalized and residual divided by to ease optimization. Highest-residual sampling may concentrate on redundant regions and does not guarantee coverage; inspect error and boundary outside collocation.
"""Helmholtz 1D manufacturado: control espectral y tres ablaciones cortas."""
import json
import time
from pathlib import Path
import numpy as np
from scipy.fft import dst, idst
import torch
from torch import nn
np.set_printoptions(precision=6)
nref=127
start_ref=time.perf_counter()
xref=np.arange(1,nref+1)/(nref+1)
true_ref=np.sin(8*np.pi*xref)
kappa=2.5*np.pi
f=(kappa**2-(8*np.pi)**2)*true_ref
lam=kappa**2-(np.pi*np.arange(1,nref+1))**2
solution=idst(dst(f,type=1,norm='ortho')/lam,type=1,norm='ortho')
spectral_seconds=time.perf_counter()-start_ref
print('referencia espectral, error relativo',np.linalg.norm(solution-true_ref)/np.linalg.norm(true_ref),flush=True)
torch.set_num_threads(1)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
dtype=torch.float64
omega=8*torch.pi
boundary=torch.tensor([[0.],[1.]],device=device,dtype=dtype)
evalx=torch.tensor(xref[:,None],device=device,dtype=dtype)
truth=torch.sin(omega*evalx)
anchor=torch.linspace(0,1,34,device=device,dtype=dtype)[1:-1,None]
candidates=torch.linspace(0,1,514,device=device,dtype=dtype)[1:-1,None]
def residual(model,x,fourier):
z=x.detach().clone().requires_grad_(True)
feature=torch.cat([z,torch.sin(omega*z),torch.cos(omega*z)],dim=1) if fourier else z
u=model(feature)
ux=torch.autograd.grad(u,z,torch.ones_like(u),create_graph=True)[0]
uxx=torch.autograd.grad(ux,z,torch.ones_like(ux),create_graph=True)[0]
source=(kappa**2-omega**2)*torch.sin(omega*z)
return (uxx+kappa**2*u-source)/(omega**2)
runs=[]
for mode in ('uniform','fourier','adaptive'):
torch.manual_seed(25)
fourier=mode=='fourier'
model=nn.Sequential(nn.Linear(3 if fourier else 1,32),nn.Tanh(),nn.Linear(32,32),nn.Tanh(),nn.Linear(32,1)).to(device=device,dtype=dtype)
optimizer=torch.optim.Adam(model.parameters(),lr=0.002)
collocation=torch.linspace(0,1,66,device=device,dtype=dtype)[1:-1,None]
started=time.perf_counter()
for step in range(1500):
if mode=='adaptive' and step%100==0:
scores=residual(model,candidates,False).detach().abs().flatten()
indices=torch.topk(scores,32).indices
collocation=torch.cat([anchor,candidates[indices]],dim=0)
feature=torch.cat([boundary,torch.sin(omega*boundary),torch.cos(omega*boundary)],dim=1) if fourier else boundary
loss=residual(model,collocation,fourier).square().mean()+10*model(feature).square().mean()
optimizer.zero_grad(set_to_none=True)
loss.backward()
optimizer.step()
if device.type=='cuda': torch.cuda.synchronize()
elapsed=time.perf_counter()-started
with torch.no_grad():
feature=torch.cat([evalx,torch.sin(omega*evalx),torch.cos(omega*evalx)],dim=1) if fourier else evalx
prediction=model(feature)
error=(torch.linalg.vector_norm(prediction-truth)/torch.linalg.vector_norm(truth)).item()
bc=(model(torch.cat([boundary,torch.sin(omega*boundary),torch.cos(omega*boundary)],dim=1) if fourier else boundary).square().mean()).item()
runs.append({'mode':mode,'relative_l2':error,'boundary_loss':bc,'seconds':elapsed})
print(mode,error,bc,flush=True)
out={'nref':nref,'spectral_error':float(np.linalg.norm(solution-true_ref)/np.linalg.norm(true_ref)), 'spectral_seconds':spectral_seconds,
'seed':25,'device':str(device),'runs':runs,
'notes':'Helmholtz no resonante, κ=2.5π; PINNs cortas con condiciones de contorno penalizadas.'}npm run lab and open the connection link.Ablation comparison
The table gathers one run of each case. In convection the Fourier reference transports sampled modes exactly and error is measured against the analytic wave at 64 positions and 21 times; each network’s space-time error uses the same norm. Allen–Cahn is measured against the 256-mode reference at the 128 common points and 21 times: its exact error is unknown here, and the 128/256 refinement differs by 0.000465. Helmholtz is measured at 127 interior nodes against the manufactured solution. Norms and problems differ; do not compare errors vertically as if they were one benchmark.
| Problem | Method | Relative error | Measured time (s) |
|---|---|---|---|
| Convection | Exact Fourier | 1.2e-15 | 0.01114 |
| Convection | Standard | 1.0921 | 69.43 |
| Convection | Causal | 1.2017 | 29.92 |
| Allen-Cahn | Fourier 256 + DOP853 | reference | 0.08535 |
| Allen-Cahn | Standard | 0.8782 | 112.84 |
| Allen-Cahn | Causal | 0.8564 | 54.90 |
| Helmholtz | Spectral sine | 1.2e-15 | 0.0004459 |
| Helmholtz | Uniform | 1.0001 | 19.48 |
| Helmholtz | Fourier | 0.00963 | 22.10 |
| Helmholtz | Adaptive | 1.0001 | 20.17 |
Times are single measurements under shared load. Training loops include initialization and saved evaluations on CUDA; the first may include startup costs. References run on CPU and measure different work: FFT at 21 times, 256-point Fourier integration or a sine-basis linear solution. They do not match tolerance or include the same costs, so the table does not prove a general speed advantage. Adaptive weighting was tested on Poisson, Fourier and resampling on Helmholtz and causality on evolution; these are not a complete factorial ablation across all three problems.
import json,time
from pathlib import Path
import numpy as np
n=64; beta=5.; x=(np.arange(n)+.5)/n; times=np.linspace(0,1,21)
start=time.perf_counter()
u0=np.sin(2*np.pi*x); modes=np.fft.fftfreq(n,d=1/n)
solution=np.fft.ifft(np.fft.fft(u0)[None,:]*np.exp(-2j*np.pi*beta*times[:,None]*modes[None,:]),axis=1).real
seconds=time.perf_counter()-start
truth=np.sin(2*np.pi*(x[None,:]-beta*times[:,None]))
error=np.linalg.norm(solution-truth)/np.linalg.norm(truth)
print('referencia espectral error',error,'tiempo',seconds)npm run lab and open the connection link.Exercises
Step 1 of 3. What is the gradient with respect to parameters?
causal_weights(losses, epsilon): for a list of nonnegative losses and nonnegative epsilon return a list with w_i = exp(−epsilon * sum of previous losses). The sum excludes the current loss.def causal_weights(losses, epsilon):
pass