-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
140 lines (122 loc) · 4.18 KB
/
test.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
#!/bin/env python
# -*- coding: utf-8 -*-
#
# Created on 03.10.22
#
# Created for ddim_for_attractors
#
# @author: Tobias Sebastian Finn, [email protected]
#
# Copyright (C) {2022} {Tobias Sebastian Finn}
# System modules
import logging
# External modules
import torch
import pytorch_lightning as pl
import hydra
from hydra.utils import instantiate
from omegaconf import DictConfig, OmegaConf
import wandb
# Internal modules
from dyn_ddim import eval_metrics
from dyn_ddim.callbacks.ema import EMA
main_logger = logging.getLogger(__name__)
def generate_predictions(
data_module: pl.LightningDataModule,
trainer: pl.Trainer,
cfg: DictConfig
) -> torch.Tensor:
main_logger.info(f"Instantiating network <{cfg.network._target_}>")
network: pl.LightningModule = instantiate(
cfg.network, _recursive_=False
)
main_logger.info(f"Load network state dict")
state_dict = torch.load(cfg.ckpt_path, map_location="cpu")
incompatible_keys = network.load_state_dict(state_dict["state_dict"])
main_logger.info(f"{incompatible_keys}")
if cfg.ema:
try:
ema_callback = EMA()
ema_callback.load_state_dict(state_dict["callbacks"]["EMA"])
ema_callback._set_ema_weights(network)
main_logger.info(f"Loaded EMA state dict from checkpoint")
except KeyError:
main_logger.warn("EMA state dict not found, using without EMA!")
main_logger.info(f"Instantiating sampler <{cfg.sampler._target_}>")
sampler = instantiate(
cfg.sampler, head=network.head, scheduler=network.scheduler,
denoising_model=network.denoising_network,
)
network.sampler = sampler
main_logger.info(f"Starting prediction")
predictions = trainer.predict(
model=network, datamodule=data_module
)
predictions = torch.cat(predictions, dim=0)
return predictions
@hydra.main(version_base=None, config_path='configs/', config_name='test')
def main_test(cfg: DictConfig):
pl.seed_everything(cfg.seed, workers=True)
main_logger.info(f"Instantiating datamodule <{cfg.data._target_}>")
data_module: pl.LightningDataModule = instantiate(cfg.data)
metric_logger = None
if OmegaConf.select(cfg, "logger") is not None:
metric_logger = instantiate(cfg.logger)
metric_logger.save()
wandb.config["seed"] = cfg.seed
main_logger.info(f"Instantiating trainer")
trainer: pl.Trainer = instantiate(
cfg.trainer,
callbacks=None,
logger=metric_logger
)
if cfg.prediction_path is None:
predictions = generate_predictions(
data_module=data_module, trainer=trainer, cfg=cfg
)
else:
data_module.setup()
predictions = torch.load(cfg.prediction_path).view(-1, 3)
surrogate_model: pl.LightningModule = instantiate(
cfg.surrogate,
)
if OmegaConf.select(cfg, "surrogate_ckpt") is not None:
surrogate_model.load_state_dict(
torch.load(cfg.surrogate_ckpt)["state_dict"]
)
surrogate_model = surrogate_model.to(trainer.strategy.root_device).eval()
metrics = {
"hellinger": eval_metrics.HellingerDistance(
reference=data_module.test_dataset,
bounds=torch.linspace(-3.5, 3.5, 71),
),
"frechet": eval_metrics.FrechetDistance(
reference=data_module.test_dataset,
network=surrogate_model.backbone,
batch_size=16384
),
"dist_test": eval_metrics.NearestCERef(
reference=data_module.test_dataset,
device=trainer.strategy.root_device
),
"dist_gen": eval_metrics.NearestCEGen(
reference=data_module.test_dataset,
device=trainer.strategy.root_device
),
"extreme": eval_metrics.ExtremeValue(
reference=data_module.test_dataset,
levels=(0.01, 0.99)
)
}
scores = {
f"test/{k:s}": metric(predictions)
for k, metric in metrics.items()
}
if metric_logger is not None:
metric_logger.log_metrics(
scores, step=0
)
main_logger.info(scores)
wandb.finish()
if __name__ == "__main__":
main_test()