Problem 1Physics-informed neural networks
100 ptsSummaryProve the analytical solution of a 1-D heat equation, then train a PINN whose loss combines PDE residual, initial-condition and boundary-condition terms, using torch.autograd.grad for derivatives and mini-batch training.
- AI for sciencePDEsAutograd
Many physics systems are governed by the following type of partial differential equations (PDEs)
where
-
: Time.
-
: Position.
-
: A function of and that is differentiable.
-
: .
-
: .
-
: A convex set in .
For such a physics system, if we know
-
Initial condition (IC)
-
for all .
-
for all (This term is required if appears in . Otherwise, it is not needed.).
-
-
Boundary condition (BC)
- for all and .
Then the value of for any and is uniquely determined.
However, many such systems do not admit closed-form solutions. The canonical approach of discretizing a PDE to find numeric solutions has many limitations.
To avoid those challenges, in this problem, you are asked to use the deep neural network approach to solve a physics-informed PDE, hereafter called as Physics-Informed Neural Network (PINN).
In this problem, let us consider the following specific 1-dim thermal system:
-
A 1-dim rod with unit length.
-
The thermal diffusivity is .
-
Two endpoints of the rod are connected to two heat reservoirs whose temperatures are constant and normalized as 0.
-
At time , the temperature distribution on the rod follows a sinusoidal pattern.
Denote by the temperature at time on position in the rod.
Thus, satisfies:
-
PDE
where
-
: .
-
: .
-
: .
-
-
IC
-
BC
Before starting this problem, make sure to run the following code first without any change:
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
import torch.optim as optim
import torch.autograd as autograd
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
-
Beyond importing libraries/modules/classes/functions in the preceeding cell, you are NOT allowed to import anything else for the following purposes:
-
As a part of your final solution. For instance, if a problem asks you to build a model without using sklearn but you use it, then you will not earn points.
-
Temporarily import something to assist you to get a solution. For instance, if a problem asks you to manually compute eigenvalues but you temporarily use
np.linalg.eigto get an answer and then delete your code, then you violate the rule.
Rule of thumb: Each part has its particular purpose to intentionally test you something. Do not attempt to find a shortcut to circumvent the rule.
-
Prove that the solution to the above PDE, IC, and BC takes the following form:
-
Reasoning is required.
-
This part is used for the purpose of verifying the correctness of our subsequent PINN solution.
Show official solutionHide solution
Official solution
First, we have
and
Hence, satisfies the PDE.
Second,
Hence, satisfies the IC.
Third,
Hence, satisfies the BC.
The high level idea of PINN is as follows:
-
(Neural network) We design a neural network (functional mapping) , such that
-
: learnable parameters in .
-
Inputs are time and position .
-
Output is the predicted temperature.
-
-
(Training data) To train (equivalently, to learn ), we use the following three groups of temporal-spacial data :
-
(Training data for PDE) are randomly sampled from .
Denote by the set of these data points.
-
(Training data for IC) with that are evenly distributed on .
Denote by the set of these data points.
-
(Training data for BC) and with that are evenly distributed on .
Denote by the set of these data points.
-
-
(Loss function in training)
where
- Residual loss in PDE:
- IC loss:
- BC loss:
In this part, you are asked to build a deep neural network that is used to output PDE solutions.
-
The class name is
HeatPINN.It subclasses
nn.Module. -
The model consists of the following layers that are sequentially conntected:
(1) Fully connected layer with
out_features = 64(you need to determinein_featurestaken from the input).(2) Activation layer with tanh function.
(3) Fully connected layer with
in_features = 64andout_features = 64.(4) Activation layer with tanh function.
(5) Fully connected layer with
in_features = 64(you need to determineout_featuresas the output of the entire model). -
Construct a model who is an object of this class and is called as
model.
Show official solutionHide solution
Official solution
class HeatPINN(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
nn.Linear(2, 64),
nn.Tanh(),
nn.Linear(64, 64),
nn.Tanh(),
nn.Linear(64, 1)
)
def forward(self, x):
return self.net(x)
model = HeatPINN()
Do the following tasks:
Let x be a tensor with shape (N,2).
-
What is the number of dimensions of
model(x)? -
What is the shape of
model(x)? -
Explain the reasoning of your answers.
Show official solutionHide solution
Official solution
-
The dimension of
model(x)is 2. -
The shape of
model(x)is(N,1). -
For each sample, the output is a 1-dim tensor with shape
(1,). Therefore, by havingNsamples, we get the answers above.
In this part, you are asked to create the dataset .
-
The dataset object is called
dataset_train_PDE. It is in a class calledDataset_PDEthat you need to build. -
Class
Dataset_PDEsubclassesDataset. -
Each is randomly sampled from .
-
Set .
Show official solutionHide solution
Official solution
num_samples = 500
class Dataset_PDE(Dataset):
def __init__(self, num_samples):
self.data = torch.rand(num_samples, 2, requires_grad=True)
def __len__(self):
return self.data.shape[0]
def __getitem__(self, idx):
return self.data[idx]
dataset_train_PDE = Dataset_PDE(num_samples)
In this part, you are asked to define a Dataloader object called dataloader_PDE:
-
dataset = dataset_train_PDE -
batch_size = 32 -
shuffle = True
Show official solutionHide solution
Official solution
batch_size_PDE = 32
dataloader_PDE = DataLoader(dataset_train_PDE, batch_size=batch_size_PDE, shuffle=True)
In this part, you are asked to create the dataset .
-
Define dataset in the way that for each , is fixed at 0 and is evenly sampled from . Therefore, .
-
The dataset shall be a tensor with name
dataset_train_ICand shape(101,2). -
Set
dataset_train_IC.requires_grad = True. -
Print
dataset_train_IC.requires_gradanddataset_train_IC.shape. -
Define tensor
u_ICto be the groud-truth functional values of all data in (You can find the formula from Part 1). -
Set
u_IC.requires_grad = Trueandu_IC.shape = (101,1). -
Print
u_IC.requires_gradandu_IC.shape.
Show official solutionHide solution
Official solution
num_samples = 101
dataset_train_IC = torch.stack([torch.zeros(num_samples), torch.linspace(0, 1, num_samples)], dim=1)
print(dataset_train_IC.requires_grad)
print(dataset_train_IC.shape)
u_IC = torch.sin(torch.pi * dataset_train_IC[:,1].view(-1,1))
u_IC.requires_grad_(True)
print(u_IC.requires_grad)
print(u_IC.shape)
In this part, you are asked to create the dataset .
-
Define dataset in the way that for each , is either 0 or 1, and is evenly sampled from . Therefore, .
-
The dataset shall be a tensor with name
dataset_train_BCand shape(202,2). -
Set
dataset_train_BC.requires_grad = True. -
Print
dataset_train_BC.requires_gradanddataset_train_IC.shape.
Show official solutionHide solution
Official solution
num_samples = 202
data_0 = torch.stack([torch.linspace(0, 1, num_samples//2), torch.zeros(num_samples//2)], dim=1)
data_1 = torch.stack([torch.linspace(0, 1, num_samples//2), torch.ones(num_samples//2)], dim=1)
dataset_train_BC = torch.cat([data_0, data_1], dim=0)
dataset_train_BC.requires_grad_(True)
print(dataset_train_BC.requires_grad)
print(dataset_train_BC.shape)
In this part, you are asked to configure your optimizer.
-
Define an optimizer object called
optimizer. -
Configure the optimization method as
Adam. -
Set the learning rate as
1e-3.
Show official solutionHide solution
Official solution
lr = 1e-3
optimizer = optim.Adam(model.parameters(), lr=lr)
The purpose of this part is to guide you to learn using torch.autograd.grad.
For each given input , we not only compute (output from the model), but also its 1st and 2nd order partial derivatives.
In PyTorch, these can be done by using torch.autograd.grad.
Part 9.1
Consider the following function
Do the following tasks at :
-
Define tensors
pandqthat have values 1.0 and 2.0 (float data type), respectively, an identical shape()(that is, 0-dim), andrequires_grad = True. -
Compute tensor
faccording to the formula above. -
Compute by using
f_p = autograd.grad(f, p, create_graph=True)[0]Print
f_p. -
Compute by using
f_q = autograd.grad(f, q, create_graph=True)[0]Print
f_q. -
Compute by using
f_pp = autograd.grad(f_p, p, create_graph=True)[0]Print
f_pp. -
Compute by using
f_qq = autograd.grad(f_q, q, create_graph=True)[0]Print out
f_qq. -
Compute by using
f_pq = autograd.grad(f_p, q, create_graph=True)[0]Print
f_pq. -
Compute by using
f_qqq = autograd.grad(f_qq, q, create_graph=True)[0]Print
f_qqq.
Part 9.2
Consider the following function
Let be a vector with values .
Do the following tasks.
-
Generate
xas a 1-dim tensor and setx.requires_grad = True. -
Generate
g = x**2. Thus,ghas the same shape asx. -
Define
g_xto be an element-wise 1st-order derivative of function with respect to . Thus,g_xhas the same shape asx.Write code to compute
g_x. Printg_xandg_x.shape.Hint: by using
autograd.grad(f, x, create_graph=True)[0], tensorxcan be with any dimension, but tensorfmust be with dimension 0. In this problem, tensorgis not with dimension 0. So you need to think about how to address this issue. -
Define
g_xxto be an element-wise 2st-order derivative of function with respect to . Thus,g_xxhas the same shape asx. Write code to computeg_xx. Print it outg_xxandg_xx.shape.
Show official solutionHide solution
Official solution
# Part 9.1
p = torch.tensor(1.0, requires_grad=True)
q = torch.tensor(2.0, requires_grad=True)
f = p**2 + q**3 + p*q**2
f_p = autograd.grad(f, p, create_graph=True)[0]
print(f_p)
f_q = autograd.grad(f, q, create_graph=True)[0]
print(f_q)
f_pp = autograd.grad(f_p, p, create_graph=True)[0]
print(f_pp)
f_qq = autograd.grad(f_q, q, create_graph=True)[0]
print(f_qq)
f_pq = autograd.grad(f_p, q, create_graph=True)[0]
print(f_pq)
f_qqq = autograd.grad(f_qq, q, create_graph=True)[0]
print(f_qqq)
# Part 9.2
x = torch.linspace(0, 1, 10)
x.requires_grad_(True)
g = x**2
g_x = autograd.grad(torch.sum(g), x, create_graph=True)[0]
print(g_x)
print(g_x.shape)
g_xx = autograd.grad(torch.sum(g_x), x, create_graph=True)[0]
print(g_xx)
print(g_xx.shape)
This part asks you to do a mini-batch training of the model.
-
Set the parameter in the PDE
alpha = 0.1. (This is not for learning. In PINN, we know the exact form of a PDE. We just need neural networks to help us solve it.) -
Set the number of epochs as 1000.
-
Define
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") -
While iterating over epochs, use
tqdmto track the progress:for epoch in tqdm(range(num_epochs)): -
In each epoch,
(1) Configure the model to the training mode.
(2) Iterate over all mini-batches of
dataset_train_PDE.(3) For each of the above mini-batch of the PDE dataset, while computing the total loss function, you also need to use all data in
dataset_train_ICanddataset_train_BC.(4) Do all these tasks on GPU.
-
In each epoch, after training over all mini-batches, if the epoch index is divisible by 100, do the following tasks:
(1) Configure the model to the evaluation mode.
(2) Compute the total loss over the entire three datasets:
dataset_train_PDE,dataset_train_IC,dataset_train_BC.(3) Print the epoch index, the residual loss from PDE, the IC loss, the BC loss, and the total loss.
(4) Do all these tasks on CPU.
Show official solutionHide solution
Official solution
alpha = 0.1
num_epochs = 1000
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
for epoch in tqdm(range(num_epochs)):
model.train()
model.to(device)
for batch_PDE in dataloader_PDE:
batch_PDE = batch_PDE.to(device)
optimizer.zero_grad()
U_PDE = model(batch_PDE)
U_t_and_x_PDE = autograd.grad(torch.sum(U_PDE), batch_PDE, create_graph=True)[0]
U_t_PDE = U_t_and_x_PDE[:,0]
U_x_PDE = U_t_and_x_PDE[:,1]
U_xx_PDE = autograd.grad(torch.sum(U_x_PDE), batch_PDE, create_graph=True)[0][:,1]
loss_PDE = torch.mean((U_t_PDE - alpha * U_xx_PDE)**2)
U_IC = model(dataset_train_IC.to(device))
loss_IC = torch.mean((U_IC - u_IC.to(device))**2)
U_BC = model(dataset_train_BC.to(device))
loss_BC = torch.mean(U_BC**2)
loss = loss_PDE + loss_IC + loss_BC
loss.backward()
optimizer.step()
if epoch % 100 == 0:
model.eval()
model.to('cpu')
batch_PDE = next(iter(dataloader_PDE))
batch_PDE.requires_grad_(True)
U_PDE = model(batch_PDE)
U_t_and_x_PDE = autograd.grad(torch.sum(U_PDE), batch_PDE, create_graph=True)[0]
U_xx_PDE = autograd.grad(torch.sum(U_t_and_x_PDE[:,1]), batch_PDE, create_graph=True)[0][:,1]
loss_PDE = torch.mean((U_t_and_x_PDE[:,0] - alpha * U_xx_PDE)**2)
with torch.no_grad():
U_IC = model(dataset_train_IC)
loss_IC = torch.mean((U_IC - u_IC)**2)
U_BC = model(dataset_train_BC)
loss_BC = torch.mean(model(dataset_train_BC)**2)
loss = loss_PDE + loss_IC + loss_BC
print(f"{loss_PDE.item():.4e}, {loss_IC.item():.4e}, {loss_BC.item():.4e}")
print(f"Epoch {epoch}, Loss: {loss.item():.4e}")
Answer the following free-response question.
- In each epoch, while iterating over each mini-batch of
dataset_PDE, why do we consider the entire data points indataset_ICanddataset_BC, rather than also a mini-batch in these two datasets?
To be specific, recall that the mini-batch size of dataset_PDE is 32. The sizes of dataset_IC and dataset_BC are 101 and 202, respectively.
Then in each iteration, the number of data points that we use to compute the total loss value is .
Suppose we also do mini-batch on the IC and BC datasets with the same mini-batch size, say, 32. Then in each iteration, the number of data points that we use is .
We adopt the former approach, not the latter approach. You need to explain why.
Show official solutionHide solution
Official solution
In training, we always need to ensure that all IC and BC constraints are satisfied. Therefore, we enforce these constraints all the time.
In this part, you are asked to do the following tasks to test the effectiveness of our PINN model.
-
Generate a dataset . Save the dataset as a tensor with name
tx_testand shape(101,2). -
For each data point, compute whose formula is given in Part 1. Save the result as a tensor with name
u_testand shape(101,2). -
For each data point, use our trained PINN model to compute the predicted value . Save the result as a tensor with name
U_testand shape(101,2). -
Print the mean squared error between
u_testandU_test. -
Generate two 2-dim scatter plots for by using the above data points.
-
In Figure 1, the value on each position is the ground-truth temperature .
-
In Figure 2, the value on each position is the predicted temperature .
-
In each plot,
-
Set
cas the values on those scattered positions -
Set
cmap='viridis' -
Add
plt.colorbar(label='Value').
-
-
Show official solutionHide solution
Official solution
model.to('cpu')
data_1dim = torch.linspace(0, 1, 101)
data_grid = torch.meshgrid(data_1dim, data_1dim)
tx_test = torch.stack([data_grid[0].reshape(-1), data_grid[1].reshape(-1)], dim=1)
u_test = torch.exp(- alpha * torch.pi**2 * tx_test[:,0]) * torch.sin(torch.pi * tx_test[:,1])
U_test = model(tx_test).reshape(-1).detach()
mse = torch.mean((u_test - U_test)**2).item()
print(mse)
plt.figure(1)
plt.scatter(tx_test[:,0], tx_test[:,1], c=u_test, cmap='viridis')
plt.xlabel('t')
plt.ylabel('x')
plt.colorbar(label='Value')
plt.title('Ground-truth')
plt.show()
plt.figure(2)
plt.scatter(tx_test[:,0], tx_test[:,1], c=U_test, cmap='viridis')
plt.xlabel('t')
plt.ylabel('x')
plt.colorbar(label='Value')
plt.title('Predicted')
plt.show()