-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
270 lines (227 loc) · 11.3 KB
/
train.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
from pathlib import Path
from tqdm import tqdm
import torch
from torch.optim import SGD
from torch.nn import MSELoss
from torch.utils.data import DataLoader
from torchvision.transforms import Resize, RandomHorizontalFlip, RandomVerticalFlip, RandomRotation
from torchmetrics import MetricCollection, PeakSignalNoiseRatio, StructuralSimilarityIndexMeasure
from torchinfo import summary
from data_loader.DataLoader import DIV2K, GaoFen2, Sev2Mod, WV3, GaoFen2panformer
from PNN import PNNmodel
from utils import *
def main():
# Prepare device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
# Initialize DataLoader
train_dataset = WV3(
Path("/home/ubuntu/project/Data/WorldView3/train/train_wv3-001.h5"), transforms=[(RandomHorizontalFlip(1), 0.3), (RandomVerticalFlip(1), 0.3)]) # /home/ubuntu/project
train_loader = DataLoader(
dataset=train_dataset, batch_size=128, shuffle=True, drop_last=True, num_workers=8)
validation_dataset = WV3(
Path("/home/ubuntu/project/Data/WorldView3/val/valid_wv3.h5"))
validation_loader = DataLoader(
dataset=validation_dataset, batch_size=16, shuffle=True)
test_dataset = WV3(Path(
"/home/ubuntu/project/Data/WorldView3/drive-download-20230627T115841Z-001/test_wv3_multiExm1.h5"))
test_loader = DataLoader(
dataset=test_dataset, batch_size=8, shuffle=False)
# Initialize Model, optimizer, criterion and metrics
model = PNNmodel(scale=4, ms_channels=8, mslr_mean=train_dataset.mslr_mean.to(device), mslr_std=train_dataset.mslr_std.to(device), pan_mean=train_dataset.pan_mean.to(device),
pan_std=train_dataset.pan_std.to(device)).to(device)
my_list = ['conv_3.weight', 'conv_3.bias']
params = list(
filter(lambda kv: kv[0] in my_list, model.parameters()))
base_params = list(
filter(lambda kv: kv[0] not in my_list, model.parameters()))
optimizer = SGD([
{'params': params},
{'params': base_params, 'lr': 5e-9}
], lr=5e-8, momentum=0.9)
criterion = MSELoss().to(device)
metric_collection = MetricCollection({
'psnr': PeakSignalNoiseRatio().to(device),
'ssim': StructuralSimilarityIndexMeasure().to(device)
})
val_metric_collection = MetricCollection({
'psnr': PeakSignalNoiseRatio().to(device),
'ssim': StructuralSimilarityIndexMeasure().to(device)
})
test_metric_collection = MetricCollection({
'psnr': PeakSignalNoiseRatio().to(device),
'ssim': StructuralSimilarityIndexMeasure().to(device)
})
tr_report_loss = 0
val_report_loss = 0
test_report_loss = 0
tr_metrics = []
val_metrics = []
test_metrics = []
best_eval_psnr = 0
best_test_psnr = 0
current_daytime = datetime.datetime.now().strftime("%Y_%m_%d-%H_%M_%S")
steps = int(1.12 * (10**6))
save_interval = 1000
report_interval = 50
test_intervals = [10000, 200000, 300000, 400000,
500000, 600000, 700000, 800000, 900000, 1000000]
evaluation_interval = [10000, 200000, 300000, 400000,
500000, 600000, 700000, 800000, 900000, 1000000]
val_steps = 50
continue_from_checkpoint = False
sum_res = summary(model, [(1, 1, 256, 256), (1, 8, 64, 64)],
dtypes=[torch.float32, torch.float32])
# load checkpoint
if continue_from_checkpoint:
tr_metrics, val_metrics, test_metrics = load_checkpoint(torch.load(
'checkpoints/pnn_model_WV3/pnn_model_2023_07_17-11_30_23_best_eval.pth.tar'), model, optimizer, tr_metrics, val_metrics, test_metrics)
print('Model Loaded ...')
print('==> Starting training ...')
train_iter = iter(train_loader)
train_progress_bar = tqdm(iter(range(steps)), total=steps, desc="Training",
leave=False, bar_format='{desc:<8}{percentage:3.0f}%|{bar:15}{r_bar}')
for step in train_progress_bar:
if step % save_interval == 0 and step != 0:
checkpoint = {'step': step,
'state_dict': model.state_dict(),
'optimizer': optimizer.state_dict(),
'tr_metrics': tr_metrics,
'val_metrics': val_metrics,
'test_metrics': test_metrics}
save_checkpoint(checkpoint, 'pnn_model_WV3', current_daytime)
try:
# Samples the batch
pan, mslr, mshr = next(train_iter)
except StopIteration:
# restart the loader if the previous loader is exhausted.
train_iter = iter(train_loader)
pan, mslr, mshr = next(train_iter)
# forward
pan, mslr, mshr = pan.to(device), mslr.to(device), mshr.to(device)
mssr = model(pan, mslr)
tr_loss = criterion(mssr, mshr)
tr_report_loss += tr_loss
batch_metric = metric_collection.forward(mssr, mshr)
# backward
optimizer.zero_grad()
tr_loss.backward()
optimizer.step()
batch_metrics = {'loss': tr_loss.item(),
'psnr': batch_metric['psnr'].item(),
'ssim': batch_metric['ssim'].item()}
# report metrics
train_progress_bar.set_postfix(
loss=batch_metrics["loss"], psnr=f'{batch_metrics["psnr"]:.4f}', ssim=f'{batch_metrics["ssim"]:.4f}')
# Store metrics
if (step + 1) % report_interval == 0 and step != 0:
# Batch metrics
tr_report_loss = tr_report_loss / (report_interval)
tr_metric = metric_collection.compute()
# store metrics
tr_metrics.append({'loss': tr_report_loss.item(),
'psnr': tr_metric['psnr'].item(),
'ssim': tr_metric['ssim'].item()})
# reset metrics
tr_report_loss = 0
metric_collection.reset()
# Evaluate model
if (step + 1) in evaluation_interval and step != 0:
# evaluation mode
model.eval()
with torch.no_grad():
print("\n==> Start evaluating ...")
val_steps = val_steps if val_steps else len(validation_loader)
eval_progress_bar = tqdm(iter(range(val_steps)), total=val_steps, desc="Validation",
leave=False, bar_format='{desc:<8}{percentage:3.0f}%|{bar:15}{r_bar}')
val_iter = iter(validation_loader)
for eval_step in eval_progress_bar:
try:
# Samples the batch
pan, mslr, mshr = next(val_iter)
except StopIteration:
# restart the loader if the previous loader is exhausted.
val_iter = iter(validation_loader)
pan, mslr, mshr = next(val_iter)
# forward
pan, mslr, mshr = pan.to(device), mslr.to(
device), mshr.to(device)
mssr = model(pan, mslr)
val_loss = criterion(mssr, mshr)
val_metric = val_metric_collection.forward(mssr, mshr)
val_report_loss += val_loss
# report metrics
eval_progress_bar.set_postfix(
loss=f'{val_loss.item()}', psnr=f'{val_metric["psnr"].item():.2f}', ssim=f'{val_metric["ssim"].item():.2f}')
# compute metrics total
val_report_loss = val_report_loss / len(validation_loader)
val_metric = val_metric_collection.compute()
val_metrics.append({'loss': val_report_loss.item(),
'psnr': val_metric['psnr'].item(),
'ssim': val_metric['ssim'].item()})
print(
f'\nEvaluation: avg_loss = {val_report_loss.item():.4f} , avg_psnr= {val_metric["psnr"]:.4f}, avg_ssim={val_metric["ssim"]:.4f}')
# reset metrics
val_report_loss = 0
val_metric_collection.reset()
print("==> End evaluating <==\n")
# train mode
model.train()
# save best evaluation model based on PSNR
if val_metrics[-1]['psnr'] > best_eval_psnr:
best_eval_psnr = val_metrics[-1]['psnr']
checkpoint = {'step': step,
'state_dict': model.state_dict(),
'optimizer': optimizer.state_dict(),
'tr_metrics': tr_metrics,
'val_metrics': val_metrics,
'test_metrics': test_metrics}
save_checkpoint(checkpoint, 'pnn_model_WV3',
current_daytime + '_best_eval')
# test model
if (step + 1) in test_intervals and step != 0:
# evaluation mode
model.eval()
with torch.no_grad():
print("\n==> Start testing ...")
test_progress_bar = tqdm(iter(test_loader), total=len(
test_loader), desc="Testing", leave=False, bar_format='{desc:<8}{percentage:3.0f}%|{bar:15}{r_bar}')
for pan, mslr, mshr in test_progress_bar:
# forward
pan, mslr, mshr = pan.to(device), mslr.to(
device), mshr.to(device)
mssr = model(pan, mslr)
test_loss = criterion(mssr, mshr)
test_metric = test_metric_collection.forward(mssr, mshr)
test_report_loss += test_loss
# report metrics
test_progress_bar.set_postfix(
loss=f'{test_loss.item()}', psnr=f'{test_metric["psnr"].item():.2f}', ssim=f'{test_metric["ssim"].item():.2f}')
# compute metrics total
test_report_loss = test_report_loss / len(test_loader)
test_metric = test_metric_collection.compute()
test_metrics.append({'loss': test_report_loss.item(),
'psnr': test_metric['psnr'].item(),
'ssim': test_metric['ssim'].item()})
print(
f'\nTesting: avg_loss = {test_report_loss.item():.4f} , avg_psnr= {test_metric["psnr"]:.4f}, avg_ssim={test_metric["ssim"]:.4f}')
# reset metrics
test_report_loss = 0
test_metric_collection.reset()
print("==> End testing <==\n")
# train mode
model.train()
# save best test model based on PSNR
if test_metrics[-1]['psnr'] > best_test_psnr:
best_test_psnr = test_metrics[-1]['psnr']
checkpoint = {'step': step,
'state_dict': model.state_dict(),
'optimizer': optimizer.state_dict(),
'tr_metrics': tr_metrics,
# 'val_metrics': val_metrics,
'test_metrics': test_metrics}
save_checkpoint(checkpoint, 'pnn_model_WV3',
current_daytime + '_best_test')
print('==> training ended <==')
if __name__ == '__main__':
main()