Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Automatic Differentiation vs Finite Differences in PINNs

Course project for APMA 2070: Deep Learning for Scientists and Engineers at Brown University.

This repository is a reproducible study of how the derivative operator used inside a physics-informed neural network (PINN) affects numerical accuracy, training stability, optimization behavior, and error attribution.

Project Thesis

In a PINN, the choice between automatic differentiation (AD) and finite differences (FDM) is not only an implementation detail. It changes the residual being optimized, the conditioning of the training problem, and the way numerical errors propagate through nonlinear PDE constraints.

The central question is:

When do AD-based and FDM-based PINNs fail for different reasons, and can those failure modes be separated into representation, optimization, and differentiation error?

Scientific Problems

Task 1: Poisson Equation

The first benchmark is a controlled Poisson problem on the unit square:

Delta u = sin(pi x) sin(pi y),    (x, y) in [0, 1]^2
u = 0                             on the boundary

The exact solution is known analytically:

u(x, y) = -sin(pi x) sin(pi y) / (2 pi^2)

This task is used to isolate differentiation error because the exact solution and exact Laplacian are available.

Task 2: Nonlinear Heat Conduction

The second benchmark is a nonlinear elliptic heat-conduction problem:

Delta T + 0.5 exp(T) = 0,         (x, y) in [0, 1]^2
T(0, y) = T(x, 0) = 1
dT/dx(1, y) = dT/dy(x, 1) = 0

This task tests stability and stiffness. The nonlinear source term exp(T) can amplify errors in the learned field and in the computed Laplacian, so the comparison between AD and FDM becomes more revealing than in the linear Poisson case.

The course handout writes the source term with the opposite sign. A finite difference audit of the provided Exact_sol_task2.npy shows that the file is consistent with Delta T + 0.5 exp(T) = 0: the relative residual of Delta T + 0.5 exp(T) is about 1.28e-2, while the residual of Delta T - 0.5 exp(T) is about 2.00. The Task 2 configs therefore use source_sign: -1.0 so the experiments evaluate against the provided reference solution.

Task 3: Resolution vs Accuracy Trade-Offs

The third benchmark returns to the Poisson problem, where an analytic solution is available, and studies whether higher-order FDM derivatives are worth their extra computational cost inside a PINN loss. The experiment compares:

  • AD,
  • second-order central FDM,
  • fourth-order central FDM.

FDM-4 uses stencil-safe collocation points so its wider stencil remains inside the physical domain. This is important because otherwise the higher-order stencil can silently evaluate the neural network outside the PDE domain.

Task 4: Failure Modes and Best Practices

The fourth benchmark turns the previous experiments into diagnostic workflow rules. It identifies:

  • an FDM failure regime where the solution is smooth and visually plausible but quantitatively wrong because the finite-difference stencil samples outside the physical domain;
  • an AD stress regime where fourth-order derivatives create substantially larger autograd graphs and higher wall-clock cost;
  • concrete guidelines for choosing AD, FDM, or a hybrid residual in scientific machine-learning workflows.

Data Provenance

This project is primarily physics-driven: the PINNs are trained from PDE residuals and boundary conditions, not from a large supervised dataset.

The only external data file expected by this repository is:

data/Exact_sol_task2.npy

This file is provided with the course project materials. It is a reference solution for Task 2, stored as a NumPy array sampled on a 100 x 100 grid over the unit square. It is used for evaluation only:

  • compare the learned T_pred(x, y) against the reference solution,
  • compute relative L2 error,
  • generate solution and error heatmaps,
  • diagnose visually plausible but quantitatively wrong PINN solutions.

It is not training data. The model should still be trained using the PDE, Dirichlet boundary conditions, and Neumann boundary conditions.

The course-provided .npy and PDF files are ignored by Git and are not redistributed in this repository.

Methodology

The implementation separates the derivative operator from the PDE loss:

  • laplacian_ad: Laplacian computed using PyTorch automatic differentiation.
  • laplacian_fdm_2nd: second-order central finite-difference Laplacian.
  • laplacian_fdm_4th: fourth-order finite-difference Laplacian for cost-vs-accuracy experiments.
  • partial_derivative_ad and second-order FDM boundary stencils: first derivatives for Neumann conditions in Task 2.

Before training PINNs, the repository runs a derivative audit on a manufactured solution:

u(x, y) = sin(pi x) sin(pi y)

This audit checks whether the derivative operators behave as expected before they are used inside a PDE-constrained training loop.

Error Attribution

The experiments are designed to separate three error sources:

  • Representation error: the neural network architecture is too small to approximate the solution well.
  • Optimization error: the optimizer fails to minimize the PINN objective reliably for a given learning rate, seed, or loss weighting.
  • Differentiation error: the PDE residual is distorted by FDM truncation error or by numerical sensitivity in higher derivatives.

This separation is the main scientific goal of the project.

Repository Layout

configs/        Experiment configurations.
data/           Local course data placement; not redistributed.
experiments/    Reproducible experiment entry points.
notebooks/      Exploration and debugging notebooks.
report/         Final report source and exported PDF.
results/        Metrics and figures generated by experiments.
scripts/        Convenience scripts for reproduction.
src/            Reusable PINN, PDE, derivative, and plotting code.
tests/          Unit tests for derivative operators and metrics.

Quick Start

Create an environment and install the package in editable mode:

python -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"

Run the derivative audit:

python experiments/run_derivative_audit.py --config configs/derivative_audit.yaml

Run a quick Task 1 pipeline check:

python experiments/run_task1_matrix.py --config configs/task1_matrix_smoke.yaml
python experiments/plot_task1_summary.py --config configs/task1_matrix_smoke.yaml

Run Task 1 baselines:

python experiments/run_task1_poisson.py --config configs/task1_poisson_ad.yaml
python experiments/run_task1_poisson.py --config configs/task1_poisson_fdm.yaml

Run the full Task 1 experiment matrix and create summary figures:

python experiments/run_task1_matrix.py --config configs/task1_matrix.yaml
python experiments/plot_task1_summary.py --config configs/task1_matrix.yaml

Run Task 2 single baselines:

python experiments/run_task2_heat.py --config configs/task2_heat_ad.yaml
python experiments/run_task2_heat.py --config configs/task2_heat_fdm.yaml

Run the full Task 2 experiment matrix and create summary figures:

python experiments/run_task2_matrix.py --config configs/task2_matrix.yaml
python experiments/plot_task2_summary.py --config configs/task2_matrix.yaml

Run the Task 3 cost-accuracy study:

python experiments/run_task3_cost_accuracy.py --config configs/task3_cost_accuracy.yaml
python experiments/plot_task3_summary.py --config configs/task3_cost_accuracy.yaml

Run the Task 4 failure-mode study:

python experiments/run_task4_failure_modes.py --config configs/task4_failure_modes.yaml
python experiments/plot_task4_summary.py --config configs/task4_failure_modes.yaml

Inspect the Task 2 reference solution:

import numpy as np
import matplotlib.pyplot as plt

T_exact = np.load("data/Exact_sol_task2.npy")
print(T_exact.shape, T_exact.min(), T_exact.max())

plt.imshow(T_exact, origin="lower", extent=[0, 1, 0, 1])
plt.colorbar(label="T")
plt.xlabel("x")
plt.ylabel("y")
plt.title("Task 2 reference solution")
plt.show()

Current Status

  • Repository skeleton and reproducibility structure are initialized.
  • AD, second-order FDM, and fourth-order FDM Laplacian operators are implemented.
  • A derivative audit is implemented and produces the first benchmark figure.
  • Task 1 Poisson baseline and full matrix runner are implemented.
  • Task 1 same-network AD/FDM derivative diagnostics are implemented.
  • Task 1 full matrix has been run for 162 configurations.
  • Task 2 nonlinear heat baseline and full matrix runner are implemented.
  • Task 2 has been run for 324 configurations: AD/FDM-2, structured/random collocation, three grids, three architectures, three learning rates, and three seeds.
  • Task 2 source-sign consistency with the provided .npy reference has been audited and documented.
  • Task 3 cost-accuracy matrix has been run for 81 configurations: AD/FDM-2/FDM-4, three resolutions, three epoch budgets, and three seeds.
  • Task 4 failure-mode diagnostics are implemented and run: FDM wide-stencil failure sweeps and AD higher-order derivative stress tests.

Academic Integrity

LLMs may be used for programming assistance only. The written reasoning, error analysis, and conclusions in the report should reflect the student's own understanding.

References

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages