This repository has been archived by the owner on Dec 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy path__init__.py
1005 lines (836 loc) · 37.6 KB
/
__init__.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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# (C) Copyright 2024 European Centre for Medium-Range Weather Forecasts.
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.
# * [WHY ARE CALLBACKS UNDER __init__.py?]
# * This functionality will be restructured in the near future
# * so for now callbacks are under __init__.py
from __future__ import annotations
import copy
import logging
import sys
import time
import traceback
import uuid
from abc import ABC
from abc import abstractmethod
from concurrent.futures import ThreadPoolExecutor
from contextlib import nullcontext
from datetime import timedelta
from functools import cached_property
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
from typing import Callable
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np
import torch
import torchinfo
from anemoi.utils.checkpoints import save_metadata
from pytorch_lightning.callbacks import Callback
from pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint
from pytorch_lightning.utilities import rank_zero_only
from anemoi.training.diagnostics.plots import init_plot_settings
from anemoi.training.diagnostics.plots import plot_graph_features
from anemoi.training.diagnostics.plots import plot_histogram
from anemoi.training.diagnostics.plots import plot_loss
from anemoi.training.diagnostics.plots import plot_power_spectrum
from anemoi.training.diagnostics.plots import plot_predicted_multilevel_flat_sample
if TYPE_CHECKING:
import pytorch_lightning as pl
from omegaconf import DictConfig
from omegaconf import OmegaConf
LOGGER = logging.getLogger(__name__)
class ParallelExecutor(ThreadPoolExecutor):
"""Wraps parallel execution and provides accurate information about errors.
Extends ThreadPoolExecutor to preserve the original traceback and line number.
Reference: https://stackoverflow.com/questions/19309514/getting-original-line-
number-for-exception-in-concurrent-futures/24457608#24457608
"""
def submit(self, fn: Any, *args, **kwargs) -> Callable:
"""Submits the wrapped function instead of `fn`."""
return super().submit(self._function_wrapper, fn, *args, **kwargs)
def _function_wrapper(self, fn: Any, *args: list, **kwargs: dict) -> Callable:
"""Wraps `fn` in order to preserve the traceback of any kind of."""
try:
return fn(*args, **kwargs)
except Exception as exc:
raise sys.exc_info()[0](traceback.format_exc()) from exc
class BasePlotCallback(Callback, ABC):
"""Factory for creating a callback that plots data to Experiment Logging."""
def __init__(self, config: OmegaConf) -> None:
"""Initialise the BasePlotCallback abstract base class.
Parameters
----------
config : OmegaConf
Config object
"""
super().__init__()
self.config = config
self.save_basedir = config.hardware.paths.plots
self.plot_frequency = config.diagnostics.plot.frequency
self.post_processors = None
self.pre_processors = None
self.latlons = None
init_plot_settings()
self.plot = self._plot
self._executor = None
if self.config.diagnostics.plot.asynchronous:
self._executor = ParallelExecutor(max_workers=1)
self._error: BaseException | None = None
self.plot = self._async_plot
@rank_zero_only
def _output_figure(
self,
logger: pl.loggers.base.LightningLoggerBase,
fig: plt.Figure,
epoch: int,
tag: str = "gnn",
exp_log_tag: str = "val_pred_sample",
) -> None:
"""Figure output: save to file and/or display in notebook."""
if self.save_basedir is not None:
save_path = Path(
self.save_basedir,
"plots",
f"{tag}_epoch{epoch:03d}.png",
)
save_path.parent.mkdir(parents=True, exist_ok=True)
fig.savefig(save_path, dpi=100, bbox_inches="tight")
if self.config.diagnostics.log.wandb.enabled:
import wandb
logger.experiment.log({exp_log_tag: wandb.Image(fig)})
if self.config.diagnostics.log.mlflow.enabled:
run_id = logger.run_id
logger.experiment.log_artifact(run_id, str(save_path))
plt.close(fig) # cleanup
def teardown(self, trainer: pl.Trainer, pl_module: pl.LightningModule, stage: str) -> None:
"""Method is called to close the threads."""
del trainer, pl_module, stage # unused
if self._executor is not None:
self._executor.shutdown(wait=True)
@abstractmethod
@rank_zero_only
def _plot(
*args: list,
**kwargs: dict,
) -> None: ...
@rank_zero_only
def _async_plot(
self,
trainer: pl.Trainer,
*args: list,
**kwargs: dict,
) -> None:
"""To execute the plot function but ensuring we catch any errors."""
future = self._executor.submit(
self._plot,
trainer,
*args,
**kwargs,
)
# otherwise the error won't be thrown till the validation epoch is finished
try:
future.result()
except Exception:
LOGGER.exception("Critical error occurred in asynchronous plots.")
sys.exit(1)
class RolloutEval(Callback):
"""Evaluates the model performance over a (longer) rollout window."""
def __init__(self, config: OmegaConf) -> None:
"""Initialize RolloutEval callback.
Parameters
----------
config : dict
Dictionary with configuration settings
"""
super().__init__()
LOGGER.debug(
"Setting up RolloutEval callback with rollout = %d, frequency = %d ...",
config.diagnostics.eval.rollout,
config.diagnostics.eval.frequency,
)
self.rollout = config.diagnostics.eval.rollout
self.frequency = config.diagnostics.eval.frequency
def _eval(
self,
pl_module: pl.LightningModule,
batch: torch.Tensor,
) -> None:
loss = torch.zeros(1, dtype=batch.dtype, device=pl_module.device, requires_grad=False)
metrics = {}
# start rollout
batch = pl_module.model.pre_processors(batch, in_place=False)
x = batch[
:,
0 : pl_module.multi_step,
...,
pl_module.data_indices.internal_data.input.full,
] # (bs, multi_step, latlon, nvar)
assert (
batch.shape[1] >= self.rollout + pl_module.multi_step
), "Batch length not sufficient for requested rollout length!"
with torch.no_grad():
for rollout_step in range(self.rollout):
y_pred = pl_module(x) # prediction at rollout step rollout_step, shape = (bs, latlon, nvar)
y = batch[
:,
pl_module.multi_step + rollout_step,
...,
pl_module.data_indices.internal_data.output.full,
] # target, shape = (bs, latlon, nvar)
# y includes the auxiliary variables, so we must leave those out when computing the loss
loss += pl_module.loss(y_pred, y)
x = pl_module.advance_input(x, y_pred, batch, rollout_step)
metrics_next, _ = pl_module.calculate_val_metrics(y_pred, y, rollout_step)
metrics.update(metrics_next)
# scale loss
loss *= 1.0 / self.rollout
self._log(pl_module, loss, metrics, batch.shape[0])
def _log(self, pl_module: pl.LightningModule, loss: torch.Tensor, metrics: dict, bs: int) -> None:
pl_module.log(
f"val_r{self.rollout}_wmse",
loss,
on_epoch=True,
on_step=True,
prog_bar=False,
logger=pl_module.logger_enabled,
batch_size=bs,
sync_dist=False,
rank_zero_only=True,
)
for mname, mvalue in metrics.items():
pl_module.log(
f"val_r{self.rollout}_" + mname,
mvalue,
on_epoch=True,
on_step=False,
prog_bar=False,
logger=pl_module.logger_enabled,
batch_size=bs,
sync_dist=False,
rank_zero_only=True,
)
@rank_zero_only
def on_validation_batch_end(
self,
trainer: pl.Trainer,
pl_module: pl.LightningModule,
outputs: list,
batch: torch.Tensor,
batch_idx: int,
) -> None:
del outputs # outputs are not used
if batch_idx % self.frequency == 0:
precision_mapping = {
"16-mixed": torch.float16,
"bf16-mixed": torch.bfloat16,
}
prec = trainer.precision
dtype = precision_mapping.get(prec)
context = torch.autocast(device_type=batch.device.type, dtype=dtype) if dtype is not None else nullcontext()
with context:
self._eval(pl_module, batch)
class GraphTrainableFeaturesPlot(BasePlotCallback):
"""Visualize the trainable features defined at the data and hidden graph nodes.
TODO: How best to visualize the learned edge embeddings? Offline, perhaps - using code from @Simon's notebook?
"""
def __init__(self, config: OmegaConf) -> None:
"""Initialise the GraphTrainableFeaturesPlot callback.
Parameters
----------
config : OmegaConf
Config object
"""
super().__init__(config)
self._graph_name_data = config.graph.data
self._graph_name_hidden = config.graph.hidden
@rank_zero_only
def _plot(
self,
trainer: pl.Trainer,
latlons: np.ndarray,
features: np.ndarray,
epoch: int,
tag: str,
exp_log_tag: str,
) -> None:
fig = plot_graph_features(latlons, features)
self._output_figure(trainer.logger, fig, epoch=epoch, tag=tag, exp_log_tag=exp_log_tag)
@rank_zero_only
def on_validation_epoch_start(self, trainer: pl.Trainer, pl_module: pl.LightningModule) -> None:
model = pl_module.model.module.model if hasattr(pl_module.model, "module") else pl_module.model.model
graph = pl_module.graph_data.cpu().detach()
epoch = trainer.current_epoch
if model.trainable_data is not None:
data_coords = np.rad2deg(graph[(self._graph_name_data, "to", self._graph_name_data)].ecoords_rad.numpy())
self.plot(
trainer,
data_coords,
model.trainable_data.trainable.cpu().detach().numpy(),
epoch=epoch,
tag="trainable_data",
exp_log_tag="trainable_data",
)
if model.trainable_hidden is not None:
hidden_coords = np.rad2deg(
graph[(self._graph_name_hidden, "to", self._graph_name_hidden)].hcoords_rad.numpy(),
)
self.plot(
trainer,
hidden_coords,
model.trainable_hidden.trainable.cpu().detach().numpy(),
epoch=epoch,
tag="trainable_hidden",
exp_log_tag="trainable_hidden",
)
class PlotLoss(BasePlotCallback):
"""Plots the unsqueezed loss over rollouts."""
def __init__(self, config: OmegaConf) -> None:
"""Initialise the PlotLoss callback.
Parameters
----------
config : OmegaConf
Object with configuration settings
"""
super().__init__(config)
self.parameter_names = None
self.parameter_groups = self.config.diagnostics.plot.parameter_groups
if self.parameter_groups is None:
self.parameter_groups = {}
@cached_property
def sort_and_color_by_parameter_group(self) -> tuple[np.ndarray, np.ndarray, dict, list]:
"""Sort parameters by group and prepare colors."""
def automatically_determine_group(name: str) -> str:
# first prefix of parameter name is group name
parts = name.split("_")
return parts[0]
# group parameters by their determined group name for > 15 parameters
if len(self.parameter_names) <= 15:
# for <= 15 parameters, keep the full name of parameters
parameters_to_groups = np.array(self.parameter_names)
sort_by_parameter_group = np.arange(len(self.parameter_names), dtype=int)
else:
parameters_to_groups = np.array(
[
next(
(
group_name
for group_name, group_parameters in self.parameter_groups.items()
if name in group_parameters
),
automatically_determine_group(name),
)
for name in self.parameter_names
],
)
unique_group_list, group_inverse, group_counts = np.unique(
parameters_to_groups,
return_inverse=True,
return_counts=True,
)
# join parameter groups that appear only once and are not given in config-file
unique_group_list = np.array(
[
unique_group_list[tn] if count > 1 or unique_group_list[tn] in self.parameter_groups else "other"
for tn, count in enumerate(group_counts)
],
)
parameters_to_groups = unique_group_list[group_inverse]
unique_group_list, group_inverse = np.unique(parameters_to_groups, return_inverse=True)
# sort parameters by groups
sort_by_parameter_group = np.argsort(group_inverse, kind="stable")
# apply new order to parameters
sorted_parameter_names = np.array(self.parameter_names)[sort_by_parameter_group]
parameters_to_groups = parameters_to_groups[sort_by_parameter_group]
unique_group_list, group_inverse, group_counts = np.unique(
parameters_to_groups,
return_inverse=True,
return_counts=True,
)
LOGGER.info("Order of parameters in loss histogram: %s", sorted_parameter_names)
# get a color per group and project to parameter list
cmap = "tab10" if len(unique_group_list) <= 10 else "tab20"
if len(unique_group_list) > 20:
LOGGER.warning("More than 20 groups detected, but colormap has only 20 colors.")
# if all groups have count 1 use black color
bar_color_per_group = (
"k" if not np.any(group_counts - 1) else plt.get_cmap(cmap)(np.linspace(0, 1, len(unique_group_list)))
)
# set x-ticks
x_tick_positions = np.cumsum(group_counts) - group_counts / 2 - 0.5
xticks = dict(zip(unique_group_list, x_tick_positions))
legend_patches = []
for group_idx, group in enumerate(unique_group_list):
text_label = f"{group}: "
string_length = len(text_label)
for ii in np.where(group_inverse == group_idx)[0]:
text_label += sorted_parameter_names[ii] + ", "
string_length += len(sorted_parameter_names[ii]) + 2
if string_length > 50:
# linebreak after 50 characters
text_label += "\n"
string_length = 0
legend_patches.append(mpatches.Patch(color=bar_color_per_group[group_idx], label=text_label[:-2]))
return sort_by_parameter_group, bar_color_per_group[group_inverse], xticks, legend_patches
@rank_zero_only
def _plot(
self,
trainer: pl.Trainer,
pl_module: pl.Lightning_module,
outputs: list[torch.Tensor],
batch: torch.Tensor,
batch_idx: int,
epoch: int,
) -> None:
logger = trainer.logger
parameter_names = list(pl_module.data_indices.internal_model.output.name_to_index.keys())
parameter_positions = list(pl_module.data_indices.internal_model.output.name_to_index.values())
# reorder parameter_names by position
self.parameter_names = [parameter_names[i] for i in np.argsort(parameter_positions)]
batch = pl_module.model.pre_processors(batch, in_place=False)
for rollout_step in range(pl_module.rollout):
y_hat = outputs[1][rollout_step]
y_true = batch[
:, pl_module.multi_step + rollout_step, ..., pl_module.data_indices.internal_data.output.full
]
loss = pl_module.loss(y_hat, y_true, squash=False).cpu().numpy()
sort_by_parameter_group, colors, xticks, legend_patches = self.sort_and_color_by_parameter_group
fig = plot_loss(loss[sort_by_parameter_group], colors, xticks, legend_patches)
self._output_figure(
logger,
fig,
epoch=epoch,
tag=f"loss_rstep_rstep{rollout_step:02d}_rank{pl_module.local_rank:01d}",
exp_log_tag=f"loss_sample_rstep{rollout_step:02d}_rank{pl_module.local_rank:01d}",
)
def on_validation_batch_end(
self,
trainer: pl.Trainer,
pl_module: pl.LightningModule,
outputs: list[torch.Tensor],
batch: torch.Tensor,
batch_idx: int,
) -> None:
if batch_idx % self.plot_frequency == 0:
self.plot(trainer, pl_module, outputs, batch, batch_idx, epoch=trainer.current_epoch)
class PlotSample(BasePlotCallback):
"""Plots a post-processed sample: input, target and prediction."""
def __init__(self, config: OmegaConf) -> None:
"""Initialise the PlotSample callback.
Parameters
----------
config : OmegaConf
Config object
"""
super().__init__(config)
self.sample_idx = self.config.diagnostics.plot.sample_idx
self.precip_and_related_fields = self.config.diagnostics.plot.precip_and_related_fields
LOGGER.info(f"Using defined accumulation colormap for fields: {self.precip_and_related_fields}")
@rank_zero_only
def _plot(
self,
trainer: pl.Trainer,
pl_module: pl.Lightning_module,
outputs: list[torch.Tensor],
batch: torch.Tensor,
batch_idx: int,
epoch: int,
) -> None:
logger = trainer.logger
# Build dictionary of indices and parameters to be plotted
diagnostics = [] if self.config.data.diagnostic is None else self.config.data.diagnostic
plot_parameters_dict = {
pl_module.data_indices.model.output.name_to_index[name]: (name, name not in diagnostics)
for name in self.config.diagnostics.plot.parameters
}
# When running in Async mode, it might happen that in the last epoch these tensors
# have been moved to the cpu (and then the denormalising would fail as the 'input_tensor' would be on CUDA
# but internal ones would be on the cpu), The lines below allow to address this problem
if self.post_processors is None:
# Copy to be used across all the training cycle
self.post_processors = copy.deepcopy(pl_module.model.post_processors).cpu()
if self.latlons is None:
self.latlons = np.rad2deg(pl_module.latlons_data.clone().cpu().numpy())
local_rank = pl_module.local_rank
batch = pl_module.model.pre_processors(batch, in_place=False)
input_tensor = batch[
self.sample_idx,
pl_module.multi_step - 1 : pl_module.multi_step + pl_module.rollout + 1,
...,
pl_module.data_indices.internal_data.output.full,
].cpu()
data = self.post_processors(input_tensor).numpy()
output_tensor = self.post_processors(
torch.cat(tuple(x[self.sample_idx : self.sample_idx + 1, ...].cpu() for x in outputs[1])),
in_place=False,
).numpy()
for rollout_step in range(pl_module.rollout):
fig = plot_predicted_multilevel_flat_sample(
plot_parameters_dict,
self.config.diagnostics.plot.per_sample,
self.latlons,
self.config.diagnostics.plot.accumulation_levels_plot,
self.config.diagnostics.plot.cmap_accumulation,
data[0, ...].squeeze(),
data[rollout_step + 1, ...].squeeze(),
output_tensor[rollout_step, ...],
precip_and_related_fields=self.precip_and_related_fields,
)
self._output_figure(
logger,
fig,
epoch=epoch,
tag=f"gnn_pred_val_sample_rstep{rollout_step:02d}_batch{batch_idx:04d}_rank0",
exp_log_tag=f"val_pred_sample_rstep{rollout_step:02d}_rank{local_rank:01d}",
)
def on_validation_batch_end(
self,
trainer: pl.Trainer,
pl_module: pl.Lightning_module,
outputs: list[torch.Tensor],
batch: torch.Tensor,
batch_idx: int,
) -> None:
if batch_idx % self.plot_frequency == 0:
self.plot(trainer, pl_module, outputs, batch, batch_idx, epoch=trainer.current_epoch)
class PlotAdditionalMetrics(BasePlotCallback):
"""Plots TP related metric comparing target and prediction.
The actual increment (output - input) is plot for prognostic variables while the output is plot for diagnostic ones.
- Power Spectrum
- Histograms
"""
def __init__(self, config: OmegaConf) -> None:
"""Initialise the PlotAdditionalMetrics callback.
Parameters
----------
config : OmegaConf
Config object
"""
super().__init__(config)
self.sample_idx = self.config.diagnostics.plot.sample_idx
self.precip_and_related_fields = self.config.diagnostics.plot.precip_and_related_fields
LOGGER.info(f"Using precip histogram plotting method for fields: {self.precip_and_related_fields}")
@rank_zero_only
def _plot(
self,
trainer: pl.Trainer,
pl_module: pl.LightningModule,
outputs: list,
batch: torch.Tensor,
batch_idx: int,
epoch: int,
) -> None:
logger = trainer.logger
# When running in Async mode, it might happen that in the last epoch these tensors
# have been moved to the cpu (and then the denormalising would fail as the 'input_tensor' would be on CUDA
# but internal ones would be on the cpu), The lines below allow to address this problem
if self.pre_processors is None:
# Copy to be used across all the training cycle
self.pre_processors = copy.deepcopy(pl_module.model.pre_processors).cpu()
if self.post_processors is None:
# Copy to be used across all the training cycle
self.post_processors = copy.deepcopy(pl_module.model.post_processors).cpu()
if self.latlons is None:
self.latlons = np.rad2deg(pl_module.latlons_data.clone().cpu().numpy())
local_rank = pl_module.local_rank
batch = pl_module.model.pre_processors(batch, in_place=False)
input_tensor = batch[
self.sample_idx,
pl_module.multi_step - 1 : pl_module.multi_step + pl_module.rollout + 1,
...,
pl_module.data_indices.internal_data.output.full,
].cpu()
data = self.post_processors(input_tensor).numpy()
output_tensor = self.post_processors(
torch.cat(tuple(x[self.sample_idx : self.sample_idx + 1, ...].cpu() for x in outputs[1])),
in_place=False,
).numpy()
for rollout_step in range(pl_module.rollout):
if self.config.diagnostics.plot.parameters_histogram is not None:
# Build dictionary of inidicies and parameters to be plotted
diagnostics = [] if self.config.data.diagnostic is None else self.config.data.diagnostic
plot_parameters_dict_histogram = {
pl_module.data_indices.model.output.name_to_index[name]: (name, name not in diagnostics)
for name in self.config.diagnostics.plot.parameters_histogram
}
fig = plot_histogram(
plot_parameters_dict_histogram,
data[0, ...].squeeze(),
data[rollout_step + 1, ...].squeeze(),
output_tensor[rollout_step, ...],
precip_and_related_fields=self.precip_and_related_fields,
)
self._output_figure(
logger,
fig,
epoch=epoch,
tag=f"gnn_pred_val_histo_rstep_{rollout_step:02d}_batch{batch_idx:04d}_rank0",
exp_log_tag=f"val_pred_histo_rstep_{rollout_step:02d}_rank{local_rank:01d}",
)
if self.config.diagnostics.plot.parameters_spectrum is not None:
# Build dictionary of inidicies and parameters to be plotted
diagnostics = [] if self.config.data.diagnostic is None else self.config.data.diagnostic
plot_parameters_dict_spectrum = {
pl_module.data_indices.model.output.name_to_index[name]: (name, name not in diagnostics)
for name in self.config.diagnostics.plot.parameters_spectrum
}
fig = plot_power_spectrum(
plot_parameters_dict_spectrum,
self.latlons,
data[0, ...].squeeze(),
data[rollout_step + 1, ...].squeeze(),
output_tensor[rollout_step, ...],
)
self._output_figure(
logger,
fig,
epoch=epoch,
tag=f"gnn_pred_val_spec_rstep_{rollout_step:02d}_batch{batch_idx:04d}_rank0",
exp_log_tag=f"val_pred_spec_rstep_{rollout_step:02d}_rank{local_rank:01d}",
)
def on_validation_batch_end(
self,
trainer: pl.Trainer,
pl_module: pl.LightningModule,
outputs: list[torch.Tensor],
batch: torch.Tensor,
batch_idx: int,
) -> None:
if batch_idx % self.plot_frequency == 0:
self.plot(trainer, pl_module, outputs, batch, batch_idx, epoch=trainer.current_epoch)
class ParentUUIDCallback(Callback):
"""A callback that retrieves the parent UUID for a model, if it is a child model."""
def __init__(self, config: OmegaConf) -> None:
"""Initialise the ParentUUIDCallback callback.
Parameters
----------
config : OmegaConf
Config object
"""
super().__init__()
self.config = config
def on_load_checkpoint(
self,
trainer: pl.Trainer,
pl_module: pl.LightningModule,
checkpoint: torch.nn.Module,
) -> None:
del trainer # unused
pl_module.hparams["metadata"]["parent_uuid"] = checkpoint["hyper_parameters"]["metadata"]["uuid"]
class AnemoiCheckpoint(ModelCheckpoint):
"""A checkpoint callback that saves the model after every validation epoch."""
def __init__(self, config: OmegaConf, **kwargs: dict) -> None:
"""Initialise the AnemoiCheckpoint callback.
Parameters
----------
config : OmegaConf
Config object
kwargs : dict
Additional keyword arguments for Pytorch ModelCheckpoint
"""
super().__init__(**kwargs)
self.config = config
self.start = time.time()
self._model_metadata = None
self._tracker_metadata = None
self._tracker_name = None
@staticmethod
def _torch_drop_down(trainer: pl.Trainer) -> torch.nn.Module:
# Get the model from the DataParallel wrapper, for single and multi-gpu cases
assert hasattr(trainer, "model"), "Trainer has no attribute 'model'! Is the Pytorch Lightning version correct?"
return trainer.model.module.model if hasattr(trainer.model, "module") else trainer.model.model
@rank_zero_only
def model_metadata(self, model: torch.nn.Module) -> dict:
if self._model_metadata is not None:
return self._model_metadata
self._model_metadata = {
"model": model.__class__.__name__,
"trainable_parameters": sum(p.numel() for p in model.parameters() if p.requires_grad),
"total_parameters": sum(p.numel() for p in model.parameters()),
"summary": repr(
torchinfo.summary(
model,
depth=50,
verbose=0,
row_settings=["var_names"],
),
),
}
return self._model_metadata
def tracker_metadata(self, trainer: pl.Trainer) -> dict:
if self._tracker_metadata is not None:
return {self._tracker_name: self._tracker_metadata}
if self.config.diagnostics.log.wandb.enabled:
self._tracker_name = "wand"
import wandb
run = wandb.run
if run is not None:
self._tracker_metadata = {
"id": run.id,
"name": run.name,
"url": run.url,
"project": run.project,
}
return {self._tracker_name: self._tracker_metadata}
if self.config.diagnostics.log.mlflow.enabled:
self._tracker_name = "mlflow"
from anemoi.training.diagnostics.mlflow.logger import AnemoiMLflowLogger
mlflow_logger = next(logger for logger in trainer.loggers if isinstance(logger, AnemoiMLflowLogger))
run_id = mlflow_logger.run_id
run = mlflow_logger._mlflow_client.get_run(run_id)
if run is not None:
self._tracker_metadata = {
"id": run.info.run_id,
"name": run.info.run_name,
"url": run.info.artifact_uri,
"project": run.info.experiment_id,
}
return {self._tracker_name: self._tracker_metadata}
return {}
def _remove_checkpoint(self, trainer: "pl.Trainer", filepath: str) -> None:
"""Calls the strategy to remove the checkpoint file."""
super()._remove_checkpoint(trainer, filepath)
trainer.strategy.remove_checkpoint(self._get_inference_checkpoint_filepath(filepath))
def _get_inference_checkpoint_filepath(self, filepath: str) -> str:
"""Defines the filepath for the inference checkpoint."""
return Path(filepath).parent / Path("inference-" + str(Path(filepath).name))
def _save_checkpoint(self, trainer: pl.Trainer, lightning_checkpoint_filepath: str) -> None:
if trainer.is_global_zero:
model = self._torch_drop_down(trainer)
# We want a different uuid each time we save the model
# so we can tell them apart in the catalogue (i.e. different epochs)
checkpoint_uuid = str(uuid.uuid4())
trainer.lightning_module._hparams["metadata"]["uuid"] = checkpoint_uuid
trainer.lightning_module._hparams["metadata"]["model"] = self.model_metadata(model)
trainer.lightning_module._hparams["metadata"]["tracker"] = self.tracker_metadata(trainer)
trainer.lightning_module._hparams["metadata"]["training"] = {
"current_epoch": trainer.current_epoch,
"global_step": trainer.global_step,
"elapsed_time": time.time() - self.start,
}
Path(lightning_checkpoint_filepath).parent.mkdir(parents=True, exist_ok=True)
save_config = model.config
model.config = None
tmp_metadata = model.metadata
model.metadata = None
metadata = dict(**tmp_metadata)
inference_checkpoint_filepath = self._get_inference_checkpoint_filepath(lightning_checkpoint_filepath)
torch.save(model, inference_checkpoint_filepath)
save_metadata(inference_checkpoint_filepath, metadata)
model.config = save_config
model.metadata = tmp_metadata
self._last_global_step_saved = trainer.global_step
trainer.strategy.barrier()
# saving checkpoint used for pytorch-lightning based training
trainer.save_checkpoint(lightning_checkpoint_filepath, self.save_weights_only)
self._last_global_step_saved = trainer.global_step
self._last_checkpoint_saved = lightning_checkpoint_filepath
if trainer.is_global_zero:
from weakref import proxy
# save metadata for the training checkpoint in the same format as inference
save_metadata(lightning_checkpoint_filepath, metadata)
# notify loggers
for logger in trainer.loggers:
logger.after_save_checkpoint(proxy(self))
def get_callbacks(config: DictConfig) -> list: # noqa: C901
"""Setup callbacks for PyTorch Lightning trainer.
Parameters
----------
config : DictConfig
Job configuration
Returns
-------
List
A list of PyTorch Lightning callbacks
"""
checkpoint_settings = {
"dirpath": config.hardware.paths.checkpoints,
"verbose": False,
# save weights, optimizer states, LR-schedule states, hyperparameters etc.
# https://pytorch-lightning.readthedocs.io/en/stable/common/checkpointing_basic.html#contents-of-a-checkpoint
"save_weights_only": False,
"auto_insert_metric_name": False,
# save after every validation epoch, if we've improved
"save_on_train_epoch_end": False,
"enable_version_counter": False,
}
ckpt_frequency_save_dict = {}
for key, frequency_dict in config.diagnostics.checkpoint.items():
frequency = frequency_dict["save_frequency"]
n_saved = frequency_dict["num_models_saved"]
if key == "every_n_minutes" and frequency_dict["save_frequency"] is not None:
target = "train_time_interval"
frequency = timedelta(minutes=frequency_dict["save_frequency"])
else:
target = key
ckpt_frequency_save_dict[target] = (config.hardware.files.checkpoint[key], frequency, n_saved)
trainer_callbacks = []
if not config.diagnostics.profiler:
for save_key, (name, save_frequency, save_n_models) in ckpt_frequency_save_dict.items():
if save_frequency is not None:
LOGGER.debug("Checkpoint callback at %s = %s ...", save_key, save_frequency)
trainer_callbacks.extend(
# save_top_k: the save_top_k flag can either save the best or the last k checkpoints
# depending on the monitor flag on ModelCheckpoint.
# See https://lightning.ai/docs/pytorch/stable/common/checkpointing_intermediate.html for reference
[
AnemoiCheckpoint(
config=config,
filename=name,
save_last=True,
**{save_key: save_frequency},
# if save_top_k == k, last k models saved; if save_top_k == -1, all models are saved
save_top_k=save_n_models,
monitor="step",
mode="max",
**checkpoint_settings,
),
],
)
else:
LOGGER.debug("Not setting up a checkpoint callback with %s", save_key)
else:
# the tensorboard logger + pytorch profiler cause pickling errors when writing checkpoints
LOGGER.warning("Profiling is enabled - will not write any training or inference model checkpoints!")
if any([config.diagnostics.log.wandb.enabled, config.diagnostics.log.mlflow.enabled]):
from pytorch_lightning.callbacks import LearningRateMonitor
trainer_callbacks.append(
LearningRateMonitor(
logging_interval="step",
log_momentum=False,
),
)
if config.diagnostics.eval.enabled:
trainer_callbacks.append(RolloutEval(config))
if config.diagnostics.plot.enabled:
trainer_callbacks.extend(
[
PlotLoss(config),
PlotSample(config),
],
)
if (config.diagnostics.plot.parameters_histogram or config.diagnostics.plot.parameters_spectrum) is not None:
trainer_callbacks.extend([PlotAdditionalMetrics(config)])
if config.training.swa.enabled:
from pytorch_lightning.callbacks.stochastic_weight_avg import StochasticWeightAveraging
trainer_callbacks.append(
StochasticWeightAveraging(
swa_lrs=config.training.swa.lr,
swa_epoch_start=min(
int(0.75 * config.training.max_epochs),
config.training.max_epochs - 1,
),
annealing_epochs=max(int(0.25 * config.training.max_epochs), 1),
annealing_strategy="cos",
device=None,
),
)
trainer_callbacks.append(ParentUUIDCallback(config))