-
Notifications
You must be signed in to change notification settings - Fork 0
/
base_model.py
454 lines (400 loc) · 16 KB
/
base_model.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
"""
Base model implementing helper methods.
"""
from collections import defaultdict
import torch
from torch import optim
from torch.utils.data import DataLoader
import numpy as np
from skimage.transform import resize
# Logging helpers
from pytorch_lightning import _logger as log
from pytorch_lightning.core import LightningModule
class BaseModel(LightningModule):
"""
The primary class containing all the training functionality. It is equivalent to\
PyTorch nn.Module in all aspects.
:param LightningModule: The Pytorch-Lightning module derived from nn.module with\
useful hooks
:type LightningModule: nn.Module
:raises NotImplementedError: Some methods must be overridden
"""
def __init__(self, hparams):
"""
Constructor for BaseModel.
:param hparams: Holds configuration values
:type hparams: Namespace
"""
# init superclass
super().__init__()
self.hparams = hparams
self.batch_size = hparams.batch_size
self.data_prepared = False
def forward(self):
"""
Dummy method to do forward pass on the model.
:raises NotImplementedError: The method must be overridden in the derived models
"""
raise NotImplementedError
def training_step(self, batch, batch_idx):
"""
Called inside the testing loop with the data from the testing dataloader \
passed in as `batch`. The implementation is delegated to the dataloader instead.
For performance critical usecase prefer monkey-patching instead.
:param model: The chosen model
:type model: Model
:param batch: Batch of input and ground truth variables
:type batch: int
:return: Loss and logs
:rtype: dict
"""
return self.data.training_step(self, batch)
def validation_step(self, batch, batch_idx):
"""
Called inside the validation loop with the data from the validation dataloader \
passed in as `batch`. The implementation is delegated to the dataloader instead.
For performance critical usecase prefer monkey-patching instead.
:param model: The chosen model
:type model: Model
:param batch: Batch of input and ground truth variables
:type batch: int
:return: Loss and logs
:rtype: dict
"""
return self.data.validation_step(self, batch)
def test_step(self, batch, batch_idx):
"""
Called inside the testing loop with the data from the testing dataloader \
passed in as `batch`. The implementation is delegated to the dataloader instead.
For performance critical usecase prefer monkey-patching instead.
:param model: The chosen model
:type model: Model
:param batch: Batch of input and ground truth variables
:type batch: int
:return: Loss and logs
:rtype: dict
"""
return (
self.data.benchmark_step(batch)
if self.hparams.benchmark
else self.data.test_step(self, batch)
)
def training_epoch_end(self, outputs):
"""
Called at the end of training epoch to aggregate outputs.
:param outputs: List of individual outputs of each training step.
:type outputs: list
:return: Loss and logs.
:rtype: dict
"""
if outputs == [{}] * len(outputs):
return {"loss": torch.zeros(1, requires_grad=True)}
avg_loss = torch.stack(
[x["_log"]["_train_loss_unscaled"] for x in outputs if x["_log"]]
).mean()
tensorboard_logs = defaultdict(dict)
tensorboard_logs["train_loss"] = avg_loss
return {
"train_loss": avg_loss,
"log": tensorboard_logs,
}
def validation_epoch_end(self, outputs):
"""
Called at the end of validation epoch to aggregate outputs.
:param outputs: List of individual outputs of each validation step.
:type outputs: list
:return: Loss and logs.
:rtype: dict
"""
if outputs == [{}] * len(outputs):
return {}
avg_loss = torch.stack([x["val_loss"] for x in outputs if x]).mean()
tensorboard_logs = defaultdict(dict)
tensorboard_logs["val_loss"] = avg_loss
for n in range(self.hparams.out_days):
tensorboard_logs[f"val_loss_{n}"] = torch.stack(
[d[str(n)] for d in [x["log"]["val_loss"] for x in outputs if x]]
).mean()
tensorboard_logs[f"val_acc_{n}"] = torch.stack(
[d[str(n)] for d in [x["log"]["acc"] for x in outputs if x]]
).mean()
tensorboard_logs[f"mae_{n}"] = torch.stack(
[d[str(n)] for d in [x["log"]["mae"] for x in outputs if x]]
).mean()
return {
"val_loss": avg_loss,
"log": tensorboard_logs,
}
def test_epoch_end(self, outputs):
"""
Called at the end of testing epoch to aggregate outputs.
:param outputs: List of individual outputs of each testing step.
:type outputs: list
:return: Loss and logs.
:rtype: dict
"""
ifx = lambda x: x if x else [torch.zeros(1)]
rm_none = lambda x: ifx([t for t in x if not torch.isnan(t).any()])
avg_loss = torch.stack(rm_none([x["mse"] for x in outputs])).mean()
tensorboard_logs = defaultdict(dict)
tensorboard_logs["mse"] = avg_loss
for n in range(self.hparams.out_days):
tensorboard_logs[f"mse_{n}"] = torch.stack(
rm_none([d[str(n)] for d in [x["log"]["mse"] for x in outputs]])
).mean()
tensorboard_logs[f"acc_{n}"] = torch.stack(
rm_none([d[str(n)] for d in [x["log"]["acc"] for x in outputs]])
).mean()
tensorboard_logs[f"mae_{n}"] = torch.stack(
rm_none([d[str(n)] for d in [x["log"]["mae"] for x in outputs]])
).mean()
# Inference on binned values
if self.hparams.binned:
for i in range(len(self.data.bin_intervals) - 1):
low, high = (
self.data.bin_intervals[i],
self.data.bin_intervals[i + 1],
)
tensorboard_logs[f"mse_{low}_{high}_{n}"] = torch.stack(
rm_none(
[
d[str(n)]
for d in [
x["log"][f"mse_{low}_{high}"] for x in outputs
]
]
)
).mean()
tensorboard_logs[f"acc_{low}_{high}_{n}"] = torch.stack(
rm_none(
[
d[str(n)]
for d in [
x["log"][f"acc_{low}_{high}"] for x in outputs
]
]
)
).mean()
tensorboard_logs[f"mae_{low}_{high}_{n}"] = torch.stack(
rm_none(
[
d[str(n)]
for d in [
x["log"][f"mae_{low}_{high}"] for x in outputs
]
]
)
).mean()
tensorboard_logs[
f"mse_{self.data.bin_intervals[-1]}_inf_{n}"
] = torch.stack(
rm_none(
[
d[str(n)]
for d in [
x["log"][f"mse_{self.data.bin_intervals[-1]}inf"]
for x in outputs
]
]
)
).mean()
tensorboard_logs[
f"acc_{self.data.bin_intervals[-1]}_inf_{n}"
] = torch.stack(
rm_none(
[
d[str(n)]
for d in [
x["log"][f"acc_{self.data.bin_intervals[-1]}inf"]
for x in outputs
]
]
)
).mean()
tensorboard_logs[
f"mae_{self.data.bin_intervals[-1]}_inf_{n}"
] = torch.stack(
rm_none(
[
d[str(n)]
for d in [
x["log"][f"mae_{self.data.bin_intervals[-1]}inf"]
for x in outputs
]
]
)
).mean()
try:
self.logger.experiment[0].log(tensorboard_logs)
except:
log.info("Logger not found, skipping the log step.")
return {
"test_loss": avg_loss,
"log": tensorboard_logs,
}
# ---------------------
# TRAINING SETUP
# ---------------------
def configure_optimizers(self):
"""
Decide optimizers and learning rate schedulers.
At least one optimizer is required.
:return: Optimizer and the schedular
:rtype: tuple
"""
if self.hparams.benchmark:
return None
optimizer = optim.Adam(self.parameters(), lr=self.hparams.learning_rate,)
if self.hparams.optim == "cosine":
scheduler = [
optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=10),
optim.lr_scheduler.ReduceLROnPlateau(
optimizer, patience=0, verbose=True, threshold=1e-1
),
]
elif self.hparams.optim == "one_cycle":
scheduler = optim.lr_scheduler.OneCycleLR(
optimizer,
max_lr=self.hparams.learning_rate,
steps_per_epoch=len(self.train_data),
epochs=self.hparams.epochs,
)
return [optimizer], [scheduler]
def add_bias(self, bias):
"""
Initialize bias parameter of the last layer with the output variable's mean.
:param bias: Mean of the output variable.
:type bias: float
"""
for w in reversed(self.state_dict().keys()):
if "bias" in w:
self.state_dict()[w].fill_(bias)
break
def prepare_data(self, ModelDataset=None, force=False):
"""
Load and split the data for training and test during the first call. Behavior \
on second call determined by the `force` parameter.
:param ModelDataset: The dataset class to be used with the model, defaults to
None
:type ModelDataset: class, optional
:param force: Force the data preperation even if already prepared, defaults to
False
:type force: bool, optional
"""
if self.data_prepared and not force:
pass
elif ModelDataset:
self.data = ModelDataset(
forecast_dir=self.hparams.forecast_dir,
forcings_dir=self.hparams.forcings_dir,
reanalysis_dir=self.hparams.reanalysis_dir,
frp_dir=self.hparams.frp_dir,
hparams=self.hparams,
out=self.hparams.out,
)
self.data.model = self
if self.hparams.cb_loss:
# Move bin_centers and freq to GPU if possible
self.data.bin_centers = torch.from_numpy(self.hparams.bin_centers).to(
self.device, dtype=next(iter(self.data))[1].dtype
)
self.data.loss_factors = torch.from_numpy(self.hparams.loss_factors).to(
self.device, dtype=next(iter(self.data))[1].dtype
)
if self.hparams.smos_input:
self.data.mask[0:105, :] = False
if self.hparams.benchmark:
self.data.input = self.data.BenchmarkDataset(
dates=self.data.dates,
forecast_dir=self.hparams.forecast_dir,
hparams=self.hparams,
).output
# Load the mask for output variable if provided or generate from NaN mask
nan_mask = ~np.isnan(
self.data.output[list(self.data.output.data_vars)[0]][0].values
)
if self.hparams.benchmark:
nan_mask &= ~np.isnan(
resize(
self.data.input[list(self.data.input.data_vars)[0]][0][
0
].values,
self.data.output[list(self.data.output.data_vars)[0]][0].shape,
)
)
if self.hparams.mask:
nan_mask &= np.load(self.hparams.mask)
self.data.mask = torch.from_numpy(nan_mask).to(self.device)
self.add_bias(self.data.out_mean)
if not hasattr(self.hparams, "eval"):
if self.hparams.chronological_split:
self.train_data = torch.utils.data.Subset(
self.data,
range(int(len(self.data) * self.hparams.chronological_split)),
)
self.test_data = torch.utils.data.Subset(
self.data,
range(
int(len(self.data) * self.hparams.chronological_split),
len(self.data),
),
)
else:
self.train_data, self.test_data = torch.utils.data.random_split(
self.data,
[
len(self.data) * (5 if self.hparams.dry_run else 8) // 10,
len(self.data)
- len(self.data) * (5 if self.hparams.dry_run else 8) // 10,
],
)
else:
self.train_data = self.test_data = self.data
self.test_data.indices = list(range(len(self.test_data)))
test_set_dates = [
str(self.data.min_date + np.timedelta64(i, "D"))
for i in self.test_data.indices
]
log.info(test_set_dates)
# Set flag to avoid resource intensive re-preparation during next call
self.data_prepared = True
def train_dataloader(self):
"""
Create the training dataloader from the training dataset.
:return: The training dataloader
:rtype: Dataloader
"""
log.info("Training data loader called.")
return DataLoader(
self.train_data,
batch_size=self.hparams.batch_size,
num_workers=0 if self.hparams.dry_run else 8,
shuffle=True,
pin_memory=True if self.hparams.gpus else False,
)
def val_dataloader(self):
"""
Create the validation dataloader from the validation dataset.
:return: The validation dataloader
:rtype: Dataloader
"""
log.info("Validation data loader called.")
return DataLoader(
self.test_data,
batch_size=self.hparams.batch_size,
num_workers=0 if self.hparams.dry_run else 8,
pin_memory=True if self.hparams.gpus else False,
)
def test_dataloader(self):
"""
Create the testing dataloader from the testing dataset.
:return: The testing dataloader
:rtype: Dataloader
"""
log.info("Test data loader called.")
return DataLoader(
self.test_data,
batch_size=self.hparams.batch_size,
num_workers=0 if self.hparams.dry_run else 8,
pin_memory=True if self.hparams.gpus else False,
)