forked from neuraloperator/physics_informed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_no.py
286 lines (248 loc) · 10.1 KB
/
train_no.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import os
import yaml
import random
from argparse import ArgumentParser
import math
from tqdm import tqdm
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader, Subset
from models import FNO3d
from train_utils.adam import Adam
from train_utils.losses import LpLoss, PINO_loss3d, get_forcing
from train_utils.datasets import NS3DDataset, KFDataset
from train_utils.utils import save_ckpt, count_params
try:
import wandb
except ImportError:
wandb = None
def pad_input(x, num_pad):
if num_pad >0:
res = F.pad(x, (0, 0, 0, num_pad), 'constant', 0)
else:
res = x
return res
def train_ns(model,
train_loader,
val_loader,
optimizer,
scheduler,
device, config, args):
# parse configuration
v = 1/ config['data']['Re']
t_duration = config['data']['t_duration']
num_pad = config['model']['num_pad']
save_step = config['train']['save_step']
ic_weight = config['train']['ic_loss']
f_weight = config['train']['f_loss']
xy_weight = config['train']['xy_loss']
# set up directory
base_dir = os.path.join('exp', config['log']['logdir'])
ckpt_dir = os.path.join(base_dir, 'ckpts')
os.makedirs(ckpt_dir, exist_ok=True)
# loss fn
lploss = LpLoss(size_average=True)
S = config['data']['pde_res'][0]
data_s_step = train_loader.dataset.dataset.data_s_step
data_t_step = train_loader.dataset.dataset.data_t_step
forcing = get_forcing(S).to(device)
# set up wandb
if wandb and args.log:
run = wandb.init(project=config['log']['project'],
entity=config['log']['entity'],
group=config['log']['group'],
config=config, reinit=True,
settings=wandb.Settings(start_method='fork'))
pbar = range(config['train']['epochs'])
pbar = tqdm(pbar, dynamic_ncols=True, smoothing=0.2)
zero = torch.zeros(1).to(device)
for e in pbar:
loss_dict = {
'train_loss': 0.0,
'ic_loss': 0.0,
'pde_loss': 0.0
}
# train
model.train()
for u, a in train_loader:
u, a = u.to(device), a.to(device)
optimizer.zero_grad()
if ic_weight == 0.0 and f_weight == 0.0:
# FNO
a_in = a[:, ::data_s_step, ::data_s_step, ::data_t_step]
out = model(a_in)
loss_ic, loss_f = zero, zero
loss = lploss(out, u)
else:
# PINO
a_in = a
out = model(a_in)
# PDE loss
u0 = a[:, :, :, 0, -1]
loss_ic, loss_f = PINO_loss3d(out, u0, forcing, v, t_duration)
# data loss
# print(out.shape)
# print(u.shape)
data_loss = lploss(out[:, ::data_s_step, ::data_s_step, ::data_t_step], u)
loss = data_loss * xy_weight + loss_f * f_weight + loss_ic * ic_weight
loss.backward()
optimizer.step()
loss_dict['train_loss'] += loss.item()
loss_dict['ic_loss'] += loss_ic.item()
loss_dict['pde_loss'] += loss_f.item()
scheduler.step()
loader_size = len(train_loader)
train_loss = loss_dict['train_loss'] / loader_size
ic_loss = loss_dict['ic_loss'] / loader_size
pde_loss = loss_dict['pde_loss'] / loader_size
# eval
model.eval()
with torch.no_grad():
val_error = 0.0
for u, a in val_loader:
u, a = u.to(device), a.to(device)
if ic_weight == 0.0 and f_weight == 0.0:
# FNO
a = a[:, ::data_s_step, ::data_s_step, ::data_t_step]
a_in = a
out = model(a_in)
data_loss = lploss(out, u)
else:
# PINO
a_in = a
out = model(a_in)
# data loss
data_loss = lploss(out[:, ::data_s_step, ::data_s_step, ::data_t_step], u)
val_error += data_loss.item()
avg_val_error = val_error / len(val_loader)
pbar.set_description(
(
f'Train loss: {train_loss}. IC loss: {ic_loss}, PDE loss: {pde_loss}, val error: {avg_val_error}'
)
)
log_dict = {
'Train loss': train_loss,
'IC loss': ic_loss,
'PDE loss': pde_loss,
'Val error': avg_val_error
}
if wandb and args.log:
wandb.log(log_dict)
if e % save_step == 0:
ckpt_path = os.path.join(ckpt_dir, f'model-{e}.pt')
save_ckpt(ckpt_path, model, optimizer)
# clean up wandb
if wandb and args.log:
run.finish()
def eval_ns(model, val_loader, device, config, args):
# parse configuration
v = 1/ config['data']['Re']
t_duration = config['data']['t_duration']
num_pad = config['model']['num_pad']
model.eval()
# loss fn
lploss = LpLoss(size_average=True)
S = config['data']['pde_res'][0]
data_s_step = val_loader.dataset.data_s_step
data_t_step = val_loader.dataset.data_t_step
with torch.no_grad():
val_error = 0.0
for u, a in tqdm(val_loader):
u, a = u.to(device), a.to(device)
# a = a[:, ::data_s_step, ::data_s_step, ::data_t_step]
a_in = a
out = model(a_in)
out = out[:, ::data_s_step, ::data_s_step, ::data_t_step]
data_loss = lploss(out, u)
val_error += data_loss.item()
avg_val_err = val_error / len(val_loader)
print(f'Average relative L2 error {avg_val_err}')
def subprocess(args):
with open(args.config, 'r') as f:
config = yaml.load(f, yaml.FullLoader)
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
# set random seed
config['seed'] = args.seed
seed = args.seed
torch.manual_seed(seed)
random.seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
# create model
model = FNO3d(modes1=config['model']['modes1'],
modes2=config['model']['modes2'],
modes3=config['model']['modes3'],
fc_dim=config['model']['fc_dim'],
layers=config['model']['layers'],
act=config['model']['act'],
pad_ratio=config['model']['pad_ratio']).to(device)
num_params = count_params(model)
config['num_params'] = num_params
print(f'Number of parameters: {num_params}')
# Load from checkpoint
if args.ckpt:
ckpt_path = args.ckpt
ckpt = torch.load(ckpt_path)
model.load_state_dict(ckpt['model'])
print('Weights loaded from %s' % ckpt_path)
datasets = {
'KF': KFDataset,
'NS': NS3DDataset
}
if 'name' in config['data']:
dataname = config['data']['name']
else:
dataname = 'NS'
if args.test:
batchsize = config['test']['batchsize']
testset = datasets[dataname](paths=config['data']['paths'],
raw_res=config['data']['raw_res'],
data_res=config['test']['data_res'],
pde_res=config['data']['pde_res'],
n_samples=config['data']['n_test_samples'],
offset=config['data']['testoffset'],
t_duration=config['data']['t_duration'])
test_loader = DataLoader(testset, batch_size=batchsize, num_workers=4, shuffle=True)
eval_ns(model, test_loader, device, config, args)
else:
# prepare datast
batchsize = config['train']['batchsize']
dataset = datasets[dataname](paths=config['data']['paths'],
raw_res=config['data']['raw_res'],
data_res=config['data']['data_res'],
pde_res=config['data']['pde_res'],
n_samples=config['data']['n_samples'],
offset=config['data']['offset'],
t_duration=config['data']['t_duration'])
idxs = torch.randperm(len(dataset))
# setup train and test
num_test = config['data']['n_test_samples']
num_train = len(idxs) - num_test
print(f'Number of training samples: {num_train};\nNumber of test samples: {num_test}.')
train_idx = idxs[:num_train]
test_idx = idxs[num_train:]
trainset = Subset(dataset, indices=train_idx)
valset = Subset(dataset, indices=test_idx)
train_loader = DataLoader(trainset, batch_size=batchsize, num_workers=4, shuffle=True)
val_loader = DataLoader(valset, batch_size=batchsize, num_workers=4)
optimizer = Adam(model.parameters(), lr=config['train']['base_lr'])
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer,
milestones=config['train']['milestones'],
gamma=config['train']['scheduler_gamma'])
print(dataset.data.shape)
train_ns(model, train_loader, val_loader,
optimizer, scheduler, device, config, args)
print('Done!')
if __name__ == '__main__':
torch.backends.cudnn.benchmark = True
# parse options
parser = ArgumentParser(description='Basic paser')
parser.add_argument('--config', type=str, help='Path to the configuration file')
parser.add_argument('--log', action='store_true', help='Turn on the wandb')
parser.add_argument('--seed', type=int, default=None)
parser.add_argument('--ckpt', type=str, default=None)
parser.add_argument('--test', action='store_true', help='Test')
args = parser.parse_args()
if args.seed is None:
args.seed = random.randint(0, 100000)
subprocess(args)