-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtrain.py
177 lines (152 loc) · 6.63 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
# ==============================================================================
# SAST: Scene Adaptive Sparse Transformer for Event-based Object Detection
# Copyright (c) 2023 The SAST Authors.
# Licensed under The MIT License.
# Written by Yansong Peng.
# Modified from RVT.
# ==============================================================================
import os
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["OPENBLAS_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["VECLIB_MAXIMUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
import torch
torch.multiprocessing.set_sharing_strategy('file_system')
from torch.backends import cuda, cudnn
cuda.matmul.allow_tf32 = True
cudnn.allow_tf32 = True
import hydra
from omegaconf import DictConfig, OmegaConf
import pytorch_lightning as pl
from pytorch_lightning.callbacks import LearningRateMonitor, ModelSummary, TQDMProgressBar
from pytorch_lightning.strategies import DDPStrategy
from callbacks.custom import get_ckpt_callback, get_viz_callback
from callbacks.gradflow import GradFlowLogCallback
from config.modifier import dynamically_modify_train_config
from data.utils.types import DatasetSamplingMode, DataType
from loggers.utils import get_wandb_logger, get_ckpt_path
from modules.utils.fetch import fetch_data_module, fetch_model_module
from pytorch_lightning.loggers import CSVLogger
import torch._dynamo.config
torch._dynamo.config.verbose=True
import sys
sys.setrecursionlimit(100000)
class MyProgressBar(TQDMProgressBar):
def init_validation_tqdm(self):
bar = super().init_validation_tqdm()
if not sys.stdout.isatty():
bar.disable = True
return bar
def init_predict_tqdm(self):
bar = super().init_predict_tqdm()
if not sys.stdout.isatty():
bar.disable = True
return bar
def init_test_tqdm(self):
bar = super().init_test_tqdm()
if not sys.stdout.isatty():
bar.disable = True
return bar
@hydra.main(config_path='config', config_name='train', version_base='1.2')
def main(config: DictConfig):
dynamically_modify_train_config(config)
# Just to check whether config can be resolved
OmegaConf.to_container(config, resolve=True, throw_on_missing=True)
print('------ Configuration ------')
print(OmegaConf.to_yaml(config))
print('---------------------------')
# ---------------------
# Reproducibility
# ---------------------
dataset_train_sampling = config.dataset.train.sampling
assert dataset_train_sampling in iter(DatasetSamplingMode)
disable_seed_everything = dataset_train_sampling in (DatasetSamplingMode.STREAM, DatasetSamplingMode.MIXED)
if disable_seed_everything:
print('Disabling PL seed everything because of unresolved issues with shuffling during training on streaming '
'datasets')
seed = config.reproduce.seed_everything
if seed is not None and not disable_seed_everything:
assert isinstance(seed, int)
print(f'USING pl.seed_everything WITH {seed=}')
pl.seed_everything(seed=seed, workers=True)
# ---------------------
# DDP
# ---------------------
gpu_config = config.hardware.gpus
gpus = OmegaConf.to_container(gpu_config) if OmegaConf.is_config(gpu_config) else gpu_config
gpus = gpus if isinstance(gpus, list) else [gpus]
distributed_backend = config.hardware.dist_backend
assert distributed_backend in ('nccl', 'gloo'), f'{distributed_backend=}'
strategy = DDPStrategy(process_group_backend=distributed_backend,
find_unused_parameters=False,
gradient_as_bucket_view=True) if len(gpus) > 1 else None
# ---------------------
# Data
# ---------------------
data_module = fetch_data_module(config=config)
# ---------------------
# Logging and Checkpoints
# ---------------------
logger = get_wandb_logger(config)
# logger = CSVLogger(save_dir='./logs/', name='experiment_name')
ckpt_path = None
if config.wandb.artifact_name is not None:
ckpt_path = get_ckpt_path(logger, wandb_config=config.wandb)
# ---------------------
# Model
# ---------------------
module = fetch_model_module(config=config)
if ckpt_path is not None and config.wandb.wandb.resume_only_weights:
print('Resuming only the weights instead of the full training state')
module = module.load_from_checkpoint(str(ckpt_path), **{'full_config': config}, strict=True)
ckpt_path = None
# ---------------------
# Callbacks and Misc
# ---------------------
callbacks = list()
callbacks.append(TQDMProgressBar(refresh_rate=100))
callbacks.append(get_ckpt_callback(config))
callbacks.append(GradFlowLogCallback(config.logging.train.log_model_every_n_steps))
if config.training.lr_scheduler.use:
callbacks.append(LearningRateMonitor(logging_interval='step'))
if config.logging.train.high_dim.enable or config.logging.validation.high_dim.enable:
viz_callback = get_viz_callback(config=config)
callbacks.append(viz_callback)
callbacks.append(ModelSummary(max_depth=2))
logger.watch(model=module, log='all', log_freq=config.logging.train.log_model_every_n_steps, log_graph=True)
# ---------------------
# Training
# ---------------------
val_check_interval = config.validation.val_check_interval
check_val_every_n_epoch = None
assert val_check_interval is None or check_val_every_n_epoch is None
trainer = pl.Trainer(
accelerator='gpu',
callbacks=callbacks,
enable_checkpointing=True,
val_check_interval=val_check_interval,
check_val_every_n_epoch=check_val_every_n_epoch,
default_root_dir='./output/',
devices=gpus,
gradient_clip_val=config.training.gradient_clip_val,
gradient_clip_algorithm='value',
limit_train_batches=config.training.limit_train_batches,
limit_val_batches=config.validation.limit_val_batches,
logger=logger,
log_every_n_steps=config.logging.train.log_every_n_steps,
plugins=None,
precision=config.training.precision,
max_epochs=config.training.max_epochs,
max_steps=config.training.max_steps,
strategy=strategy,
sync_batchnorm=False if strategy is None else True,
move_metrics_to_cpu=False,
benchmark=config.reproduce.benchmark,
deterministic=config.reproduce.deterministic_flag,
auto_scale_batch_size=False
)
trainer.fit(model=module, ckpt_path=ckpt_path, datamodule=data_module)
if __name__ == '__main__':
main()