-
Notifications
You must be signed in to change notification settings - Fork 7
/
main_h.py
162 lines (136 loc) · 5.51 KB
/
main_h.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
import logging
from pathlib import Path
import random
import numpy as np
import hydra
import pytorch_lightning as pl
import torch
import wandb
import random
import numpy as np
### seed
seed = 42
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
from omegaconf import DictConfig, OmegaConf
from pytorch_lightning.callbacks import Callback, ModelCheckpoint, RichProgressBar, LearningRateMonitor
from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning.strategies import DDPStrategy
from torch.distributed.algorithms.ddp_comm_hooks import default_hooks as default
from src.dataset_h import LivenessDatamodule
from src.model_h import TIMMModel
log = logging.getLogger(__name__)
def set_debug_apis(state: bool = False):
torch.autograd.profiler.profile(enabled=state)
torch.autograd.profiler.emit_nvtx(enabled=state)
torch.autograd.set_detect_anomaly(mode=state)
class LogPredictionSamplesCallback(Callback):
def __init__(self, wandb_logger, samples=8) -> None:
super().__init__()
self.wandb_logger: WandbLogger = wandb_logger
self.samples = samples
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx):
if batch_idx == 0:
n = self.samples
cleaned, _ = batch
cleaned_hat, hazed_synth = outputs["cleaned_hat"], outputs["hazed_synth"]
images = [
torch.cat([hazed_inp, cleaned_pred, cleaned_gt], dim=-1)
for hazed_inp, cleaned_pred, cleaned_gt in zip(
hazed_synth[:n], cleaned_hat[:n], cleaned[:n]
)
]
captions = ["Inp - Pred - GT"] * n
# Option 1: log images with `WandbLogger.log_image`
self.wandb_logger.log_image(
key="train/visualization", images=images, caption=captions
)
def on_validation_batch_end(
self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx
):
"""Called when the validation batch ends."""
# `outputs` comes from `LightningModule.validation_step`
# which corresponds to our model predictions in this case
# Let's log image predictions from the first batch
if batch_idx == 0:
n = self.samples
cleaned, hazed = batch
cleaned_hat = outputs
images = [
torch.cat([hazed_inp, cleaned_pred, cleaned_gt], dim=-1)
for hazed_inp, cleaned_pred, cleaned_gt in zip(
hazed[:n], cleaned_hat[:n], cleaned[:n]
)
]
captions = ["Inp - Pred - GT"] * n
# Option 1: log images with `WandbLogger.log_image`
self.wandb_logger.log_image(
key="val/visualization", images=images, caption=captions
)
def train(config):
# config.seed = pl.seed_everything(seed=config.seed, workers=True)
wandb_logger = WandbLogger(
project="zalo_2022",
log_model=False,
settings=wandb.Settings(start_method="fork"),
name=Path.cwd().stem,
dir=Path.cwd()
)
# Create callbacks
callbacks = []
callbacks.append(ModelCheckpoint(**config.model_ckpt))
callbacks.append(RichProgressBar(config.refresh_rate))
callbacks.append(LearningRateMonitor(logging_interval='epoch'))
# callbacks.append(LogPredictionSamplesCallback(wandb_logger))
OmegaConf.set_struct(config, False)
strategy = config.trainer.pop("strategy", None)
OmegaConf.set_struct(config, True)
if strategy == "ddp" and config.trainer.accelerator == "gpu":
# When using a single GPU per process and per
# DistributedDataParallel, we need to divide the batch size
# ourselves based on the total number of GPUs we have
# TODO: Currently only handles gpus = -1 or an int number
if config.trainer.devices == -1:
config.trainer.devices = torch.cuda.device_count()
num_nodes = getattr(config.trainer, "num_nodes", 1)
total_gpus = max(1, config.trainer.devices * num_nodes)
config.dataset.batch_size = int(config.dataset.batch_size / total_gpus)
config.dataset.num_workers = int(config.dataset.num_workers / total_gpus)
strategy = DDPStrategy(
find_unused_parameters=config.ddp_plugin.find_unused_params,
gradient_as_bucket_view=True,
ddp_comm_hook=default.fp16_compress_hook
if config.ddp_plugin.fp16_hook
else None,
static_graph=config.ddp_plugin.static_graph,
)
model = TIMMModel(config.model)
datamodule = LivenessDatamodule(config.dataset)
trainer = pl.Trainer(
logger=wandb_logger,
callbacks=callbacks,
strategy=strategy,
**config.trainer,
)
wandb_logger.watch(model, log="parameters", log_graph=False)
trainer.fit(model, datamodule=datamodule)
wandb.finish()
@hydra.main(config_path="configs", config_name="baseline_h")
def main(config: DictConfig) -> None:
log.info("Zalo AI Challenge - Liveness Detection")
log.info(f"Current working directory : {Path.cwd()}")
wandb.login(key="933604722ded3597941c3c3cf19b15d688d6e425")
if config.state == "train":
set_debug_apis(state=False)
train(config)
elif config.state == "debug":
pass
elif config.state == "test":
set_debug_apis(state=False)
pass
if __name__ == "__main__":
main()