Show code cell source
import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib_inline
matplotlib_inline.backend_inline.set_matplotlib_formats('svg')
import seaborn as sns
sns.set_context("paper")
sns.set_style("ticks");
!pip show equinox || echo equinox not found. Installing... && pip install equinox 2> /dev/null
Show code cell output
Name: equinox
Version: 0.11.2
Summary: Elegant easy-to-use neural networks in JAX.
Home-page:
Author:
Author-email: Patrick Kidger <contact@kidger.site>
License: Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Location: /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages
Requires: jax, jaxtyping, typing-extensions
Required-by: diffrax, lineax, optimistix, orthojax
Requirement already satisfied: equinox in /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages (0.11.2)
Requirement already satisfied: jax>=0.4.13 in /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages (from equinox) (0.4.19)
Requirement already satisfied: jaxtyping>=0.2.20 in /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages (from equinox) (0.2.25)
Requirement already satisfied: typing-extensions>=4.5.0 in /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages (from equinox) (4.8.0)
Requirement already satisfied: ml-dtypes>=0.2.0 in /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages (from jax>=0.4.13->equinox) (0.3.1)
Requirement already satisfied: numpy>=1.22 in /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages (from jax>=0.4.13->equinox) (1.25.2)
Requirement already satisfied: opt-einsum in /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages (from jax>=0.4.13->equinox) (3.3.0)
Requirement already satisfied: scipy>=1.9 in /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages (from jax>=0.4.13->equinox) (1.11.3)
Requirement already satisfied: typeguard<3,>=2.13.3 in /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages (from jaxtyping>=0.2.20->equinox) (2.13.3)
Physics-Informed Neural Networks (PINNs) - Forward Problems#
We can use PINNs to solve forward problems in place of traditional numerical methods. This is not recommended, as PINNs are not yet as efficient as traditional numerical methods. But, it is a good way to learn how to use PINNs and to understand their limitations. Throughout this section we will be following closely the methodology of Wang et al. (2023).
The toy problem - Steady-state heat equation#
We are going to solve a Poisson’s equation with a source term:
Making an exact solution#
We will use a common trick to construct an exact solution. We will use the following function:
The boundary conditions are satisfied by construction. The source term is:
Show code cell source
import sympy
xs, ys, ks, u0s, Lxs, Lys = sympy.symbols('x y k u_0 L_x L_y')
us = u0s * sympy.sin(sympy.pi * xs / Lxs) ** 2 * sympy.sin(sympy.pi * ys / Lys) ** 2
fs = -ks * (sympy.diff(us, xs, 2) + sympy.diff(us, ys, 2))
sympy.simplify(fs)
This is a common trick for constructing exact solutions. Remember it!
Let’s use the following parameters:
u0 = 500 # degrees Kelvin
k = 10.0 # thermal conductivity in W/mK
Lx = 0.1 # meters
Ly = 1.0 # meters
Enforcing the boundary conditions#
We are going to solve this boundary value problem using PINNS. Our model will be:
where \(\text{MLP}(x, y)\) is a multi-layer perceptron, and \(x(1-x)y(1-y)\) is a polynomial that satisfies the boundary conditions. This is also a common trick for enforcing boundary conditions in PINNS.
Multi-layer perceptron#
We will be using a simple multi-layer perceptron to represent the solution of a PDE. The architecture of the network is given by:
where
The terms \(W^{(l)}\) and \(b^{(l)}\) are the weights and biases of the \(l\)-th layer, and \(g^{(l)}\) is the activation function of the \(l\)-th layer. The parameters \(\theta\) are the weights and biases of the network:
For PINNS applications, it is recommended that:
We use the tanh activation function all layers.
We use 128 to 512 neurons per layer.
We use 3 to 5 layers.
Use the Glorot initialization (this is the default in
equinox
).
Let’s make the model:
import equinox as eqx
import jax.numpy as jnp
import jax.random as jrandom
key = jrandom.PRNGKey(0)
key, subkey = jrandom.split(key)
# MLP parameters
width_size = 128
depth = 4
mlp = eqx.nn.MLP(2, 1, width_size, depth, jnp.tanh, key=subkey)
# This is the parameterization of the solution that satisfies the boundary conditions
u_hat = lambda x, y, mlp: x * (Lx - x) * y * (Ly - y) * mlp(jnp.array([x, y]))[0]
Let’s see how it looks like before we train it:
Show code cell source
from jax import vmap
v_u_hat = eqx.filter_jit(vmap(u_hat, in_axes=(0, 0, None)))
x = jnp.linspace(0, Lx, 100)
y = jnp.linspace(0, Ly, 100)
X, Y = jnp.meshgrid(x, y)
u_pred = v_u_hat(X.flatten(), Y.flatten(), mlp).reshape(X.shape)
# the true solution for comparison
u_true = u0 * jnp.sin(jnp.pi * X / Lx) ** 2 * jnp.sin(jnp.pi * Y / Ly) ** 2
fig, ax = plt.subplots(1,2)
c = ax[0].contourf(X, Y, u_pred, cmap='viridis')
fig.colorbar(c, ax=ax[0])
ax[0].set_xlabel('x')
ax[0].set_ylabel('y')
ax[0].set_title('Initial point')
sns.despine(trim=True);
c = ax[1].contourf(X, Y, u_true, cmap='viridis', levels=jnp.linspace(0, 560, 10))
fig.colorbar(c, ax=ax[1])
ax[1].set_xlabel('x')
ax[1].set_ylabel('y')
ax[1].set_title('True solution')
sns.despine(trim=True)
plt.tight_layout();
Setting up the loss function#
We are going to train this by minimizing the following loss function:
The first step, is to turn the loss function into an expectation. Construct the random variable \(\mathbf{X} = (X,Y)\) uniformly distributed in \(\Omega\). Then, the loss function can be written as:
Notice that the volume of \(\Omega\), \(\Omega|\), appears as a constant factor. Where did it come from? Recall the probability density function of \(\mathbf{X}\) is:
So:
We can approximate this expectation by sampling a finite number of points from \(\Omega\) and averaging the loss function over these points. This is what we will be doing in each iteration of the training process.
from jax import grad
# First order derivatives
u_x = grad(u_hat, argnums=0)
u_y = grad(u_hat, argnums=1)
# Second order deerivatives
u_xx = grad(u_x, argnums=0)
u_yy = grad(u_y, argnums=1)
# The Laplacian
D2_u = lambda x, y, mlp: u_xx(x, y, mlp) + u_yy(x, y, mlp)
# The source term
source_term = lambda x, y: 2.0 * jnp.pi ** 2 * k * u0 * (
-Lx ** 2 * jnp.sin(jnp.pi * x / Lx) ** 2 * jnp.cos(2.0 * jnp.pi * y / Ly)
-Ly ** 2 * jnp.sin(jnp.pi * y / Ly) ** 2 * jnp.cos(2.0 * jnp.pi * x / Lx)
) / (Lx ** 2 * Ly ** 2)
# The PDE residual (vectorize)
pde_residual = vmap(
lambda x, y, mlp: D2_u(x, y, mlp) + source_term(x, y),
in_axes=(0, 0, None))
# Finally the loss function:
loss = lambda mlp, x, y: Lx * Ly * jnp.mean(jnp.square(pde_residual(x, y, mlp)))
Training the model#
We will use the ADAM optimizer with standard parameters. This is the training algorithm:
def train(
loss,
mlp,
key,
optimizer,
Lx=1.0,
Ly=1.0,
num_collocation_residual=512,
num_iter=10_000,
freq=1,
):
@eqx.filter_jit
def step(opt_state, mlp, xs, ys):
value, grads = eqx.filter_value_and_grad(loss)(mlp, xs, ys)
updates, opt_state = optimizer.update(grads, opt_state)
mlp = eqx.apply_updates(mlp, updates)
return mlp, opt_state, value
opt_state = optimizer.init(eqx.filter(mlp, eqx.is_inexact_array))
losses = []
for i in range(num_iter):
key, subkey = jrandom.split(key)
xb = jrandom.uniform(subkey, (num_collocation_residual,), maxval=Lx)
key, subkey = jrandom.split(key)
yb = jrandom.uniform(subkey, (num_collocation_residual,), maxval=Ly)
mlp, opt_state, value = step(opt_state, mlp, xb, yb)
if i % freq == 0:
losses.append(value)
print(f"Step {i}, residual loss {value:.3e}")
return mlp, losses
And this is the actual trainning:
import optax
optimizer = optax.adam(1e-3)
trained_mlp, losses = train(loss, mlp, key, optimizer, num_collocation_residual=256, num_iter=1_000, freq=100, Lx=Lx, Ly=Ly)
Step 0, residual loss 1.694e+12
Step 100, residual loss 1.799e+12
Step 200, residual loss 1.611e+12
Step 300, residual loss 1.676e+12
Step 400, residual loss 1.715e+12
Step 500, residual loss 1.520e+12
Step 600, residual loss 1.874e+12
Step 700, residual loss 2.111e+12
Step 800, residual loss 1.660e+12
Step 900, residual loss 1.762e+12
Let’s visualize first the evolution of the loss function:
Show code cell source
fig, ax = plt.subplots()
ax.plot(losses)
ax.set_xlabel('Iteration x 100')
ax.set_ylabel('Residual loss')
sns.despine(trim=True);
It’s not working! The loss function is not decreasing. Here is also the trained “solution:”
Show code cell source
fig, ax = plt.subplots(1,2)
u_pred = v_u_hat(X.flatten(), Y.flatten(), trained_mlp).reshape(X.shape)
c = ax[0].contourf(X, Y, u_pred, cmap='viridis')
fig.colorbar(c, ax=ax[0])
ax[0].set_xlabel('x')
ax[0].set_ylabel('y')
ax[0].set_title('Trained solution')
sns.despine(trim=True);
c = ax[1].contourf(X, Y, u_true, cmap='viridis', levels=jnp.linspace(0, 560, 10))
fig.colorbar(c, ax=ax[1])
ax[1].set_xlabel('x')
ax[1].set_ylabel('y')
ax[1].set_title('True solution')
sns.despine(trim=True)
plt.tight_layout();
Non-dimensionalization of Partial Differential Equations#
The problem is that the initialization of the network weights is completely off. Glorot initialization is assuming that the input data and the output data are scaled to be around zero (scale of about 1). To get our problem to that scale, we need to non-dimensionalize it.
We start by picking characteristic lengthscales. Here, it makes sense to pick \(L_x\) and \(L_y\) as characteristic lengthscales. We also need to pick a characteristic value for the temperature, say \(u_s\).
The next step is to find the partial derivatives of \(u\) with respect to \(x\) and \(y\) in terms of the non-dimensional variables:
Here, we just used the chain rule.
The second derivatives are:
Plugging these into the original PDE, we get:
Define now the non-dimensional source term:
And the non-dimensional thermal conductivity:
The equation becomes:
defined on the non-dimensional domain \(\tilde{\Omega} = [0, 1]\times [0, 1]\).
Now we need to pick \(u_s\) and \(f_s\) so that both sides of the equation are of order one. We can easily make the lef-hand side to be of order one by picking:
For the left-hand side, we can pick \(u_s\) so that:
Solving for \(u_s\), we get that \(u_s\) should be of the order:
Do not take the equality sign too seriously. All we need is that \(u_s\) is of the order of the right-hand side of the equation.
Let’s find these numbers:
# These functions convert from x to xt and y to yt and vice versa
to_x = lambda xt: xt * Lx
to_y = lambda yt: yt * Ly
to_xt = lambda x: x / Lx
to_yt = lambda y: y / Ly
Xt = to_xt(X)
Yt = to_yt(Y)
fs = jnp.abs(source_term(X.flatten(), Y.flatten())).max()
# Start a random MLP
tmlp = eqx.nn.MLP(2, 1, width_size, depth, jnp.tanh, key=subkey)
tu_hat = lambda tx, ty, tmlp: tx * (1.0 - tx) * ty * (1.0 - ty) * tmlp(jnp.array([tx, ty]))[0]
# Find the required gradients
tu_x = grad(tu_hat, argnums=0)
tu_y = grad(tu_hat, argnums=1)
tu_xx = grad(tu_x, argnums=0)
tu_yy = grad(tu_y, argnums=1)
v_tu_xx = eqx.filter_jit(vmap(u_xx, in_axes=(0, 0, None)))
v_tu_yy = eqx.filter_jit(vmap(u_yy, in_axes=(0, 0, None)))
max_u_xx = jnp.abs(v_tu_xx(Xt.flatten(), Yt.flatten(), tmlp).reshape(X.shape)).max()
max_u_yy = jnp.abs(v_tu_yy(Xt.flatten(), Yt.flatten(), tmlp).reshape(X.shape)).max()
# Calculate the scale:
us = fs / k / max(max_u_xx, max_u_yy) / max(1/Lx**2, 1/Ly**2)
print(f"Scale factor fs: {fs:.2e}")
print(f"Scale factor us: {us:.2e}")
Scale factor fs: 9.96e+06
Scale factor us: 4.40e+04
Let’s check if the left hand side is comparable to the right hand side:
lhs = lambda tx, ty, tmlp: -k * us / fs * (1.0 / Lx ** 2 * tu_xx(tx, ty, tmlp) + 1.0 / Ly ** 2 * tu_yy(tx, ty, tmlp))
v_lhs = eqx.filter_jit(vmap(lhs, in_axes=(0, 0, None)))
fig, ax = plt.subplots(1,2)
tl = v_lhs(Xt.flatten(), Yt.flatten(), tmlp).reshape(X.shape)
c = ax[0].contourf(Xt, Yt, tl, cmap='viridis')
fig.colorbar(c, ax=ax[0])
ax[0].set_xlabel(r'$\tilde{x}$')
ax[0].set_ylabel(r'$\tilde{y}$')
ax[0].set_title('Left-hand side')
tf = source_term(X.flatten(), Y.flatten()).reshape(X.shape) / fs
c = ax[1].contourf(Xt, Yt, tf, cmap='viridis')
fig.colorbar(c, ax=ax[1])
ax[1].set_xlabel(r'$\tilde{x}$')
ax[1].set_ylabel(r'$\tilde{y}$')
ax[1].set_title('Scaled source term')
sns.despine(trim=True)
plt.tight_layout();
This looks pretty good as a starting point!
Here is what the scaled conductivity looks like:
tkx = (k * us) / (Lx ** 2 * fs)
tky = (k * us) / (Ly ** 2 * fs)
print(f"tkx = {tkx:.3e}, tky = {tky:.3e}")
tkx = 4.415e+00, tky = 4.415e-02
Let’s now try training the scaled version of the problem:
tmlp = eqx.nn.MLP(2, 1, width_size, depth, jnp.tanh, key=subkey)
tu_hat = lambda tx, ty, tmlp: tx * (1.0 - tx) * ty * (1.0 - ty) * tmlp(jnp.array([tx, ty]))[0]
tu_x = grad(tu_hat, argnums=0)
tu_y = grad(tu_hat, argnums=1)
tu_xx = grad(tu_x, argnums=0)
tu_yy = grad(tu_y, argnums=1)
tilde_source_term = lambda tx, ty: source_term(to_x(tx), to_y(ty)) / fs
tpde_residual = vmap(
lambda tx, ty, tmlp: tkx * tu_xx(tx, ty, tmlp) + tky * tu_yy(tx, ty, tmlp) + tilde_source_term(tx, ty),
in_axes=(0, 0, None))
tloss = lambda tmlp, tx, ty: jnp.mean(jnp.square(tpde_residual(tx, ty, tmlp)))
optimizer = optax.adam(1e-3)
trained_tmlp, losses = train(tloss, tmlp, key, optimizer, num_collocation_residual=256, num_iter=2_000, freq=100, Lx=1.0, Ly=1.0)
Step 0, residual loss 1.776e-01
Step 100, residual loss 2.152e-02
Step 200, residual loss 1.609e-02
Step 300, residual loss 9.821e-03
Step 400, residual loss 8.162e-03
Step 500, residual loss 1.964e-03
Step 600, residual loss 1.231e-03
Step 700, residual loss 3.521e-04
Step 800, residual loss 2.916e-04
Step 900, residual loss 1.718e-04
Step 1000, residual loss 2.290e-04
Step 1100, residual loss 2.774e-04
Step 1200, residual loss 1.921e-04
Step 1300, residual loss 1.431e-04
Step 1400, residual loss 1.637e-04
Step 1500, residual loss 2.281e-04
Step 1600, residual loss 1.966e-04
Step 1700, residual loss 1.857e-04
Step 1800, residual loss 1.171e-04
Step 1900, residual loss 4.257e-04
Note
If you are running this on Google Colab Pro, try using an A100 GPU. On my M1 Macbook Pro, the training takes about 17.5s. On an A100 GPU, it takes about 8s.
I save this loss for the next notebook.
import numpy as np
np.savez("mlp_losses.npz", losses=losses)
Here is the loss function:
fig, ax = plt.subplots()
ax.plot(losses)
ax.set_xlabel('Iteration x 100')
ax.set_ylabel('Residual loss')
sns.despine(trim=True);
And here is the solution scaled back to the original domain:
v_tu_hat = vmap(tu_hat, in_axes=(0, 0, None))
fig, ax = plt.subplots(1,2)
u_pred = v_tu_hat(to_xt(X.flatten()), to_yt(Y.flatten()), trained_tmlp).reshape(X.shape)
c = ax[0].contourf(X, Y, u_pred * us, cmap='viridis',
levels=jnp.linspace(-1, 510.0, 10))
fig.colorbar(c, ax=ax[0])
ax[0].set_xlabel('x')
ax[0].set_ylabel('y')
ax[0].set_title('Trained solution')
sns.despine(trim=True);
c = ax[1].contourf(X, Y, u_true, cmap='viridis',
levels=jnp.linspace(-1, 510.0, 10))
fig.colorbar(c, ax=ax[1])
ax[1].set_xlabel('x')
ax[1].set_ylabel('y')
ax[1].set_title('Scaled true solution')
sns.despine(trim=True)
plt.tight_layout();
The point wise error is here:
fig, ax = plt.subplots()
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('Trained solution')
c = ax.contourf(to_xt(X), to_yt(Y), jnp.abs(u_pred * us - u_true), cmap='viridis')
plt.colorbar(c, ax=ax)
sns.despine(trim=True);
It is very hard to achieve better error with plain MLPs.