forked from rapidrabbit76/Classification-For-Everyone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
192 lines (158 loc) · 6.06 KB
/
main.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
import os
from argparse import ArgumentParser
from typing import *
from unicodedata import name
import pytorch_lightning as pl
import torch
from pytorch_lightning.callbacks import (
EarlyStopping,
LearningRateMonitor,
ModelCheckpoint,
TQDMProgressBar,
)
from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning.utilities.seed import seed_everything
from datamodules import *
from models import *
from transforms import *
def hyperparameters():
parser = ArgumentParser()
parser = pl.Trainer.add_argparse_args(parser)
add = parser.add_argument
ds_candidate = list(DATAMODULE_TABLE.keys())
model_candidate = list(MODEL_TABLE.keys())
transfoms_candidate = list(TRANSFORMS_TABLE.keys())
# experiment hyperparameters
## experiment
add("--seed", type=int, default=9423)
add("--experiment_name", type=str)
add("--root_dir", type=str)
## data module/set/transforms
add("--dataset", type=str, choices=ds_candidate)
add("--transforms", type=str, choices=transfoms_candidate)
add("--num_workers", type=int, default=16)
add("--image_channels", type=int, default=3)
add("--image_size", type=int)
add("--batch_size", type=int, default=64)
## each model
add("--model", type=str, choices=model_candidate)
add("--model_type", type=str)
add("--num_classes", type=int)
add("--dropout_rate", type=float, default=0.5)
## WideResNet
add("--depth", type=int, default=40)
add("--K", type=int, default=10)
## Inception
add("--loss_w", type=float, default=0.5)
add("--aux_loss_w", type=float, default=0.5)
## Densenet
add("--growth_rate", type=int, default=12)
## callbacks
add("--callbacks_verbose", action="store_true")
add("--callbacks_refresh_rate", type=int, default=5)
add("--callbacks_save_top_k", type=int, default=3)
add("--callbacks_monitor", type=str, default="val/acc")
add("--callbacks_mode", type=str, default="max")
add("--earlystooping_min_delta", type=float, default=0.02)
add("--earlystooping_patience", type=int, default=10)
## optimizer
add("--lr", type=float, default=0.1)
add("--lr_scheduler_gamma", type=float, default=0.2)
add("--scheduler_interval", type=str, default="epoch")
add("--scheduler_frequency", type=int, default=10)
## ReduceLROnPlateau
add("--scheduler_mode", type=str, default="min")
add("--scheduler_factor", type=float, default=0.1)
add("--scheduler_patience", type=int, default=5)
add("--scheduler_monitor", type=str, default="val/loss")
### SGD
add("--momentum", type=float, default=0)
add("--weight_decay", type=float, default=0)
add("--nesterov", action="store_true")
args = pl.Trainer.parse_argparser(parser.parse_args())
return args
def main(args):
transforms = TRANSFORMS_TABLE[args.transforms]
datamodule = DATAMODULE_TABLE[args.dataset]
model = MODEL_TABLE[args.model]
seed_everything(args.seed)
######################### BUILD DATAMODULE ##############################
image_shape = [args.image_channels, args.image_size, args.image_size]
train_transforms = transforms(image_shape=image_shape, train=True)
val_transforms = transforms(image_shape=image_shape, train=False)
test_transforms = transforms(image_shape=image_shape, train=False)
datamodule = datamodule(
root_dir=args.root_dir,
train_transforms=train_transforms,
val_transforms=val_transforms,
test_transforms=test_transforms,
batch_size=args.batch_size,
num_workers=args.num_workers,
)
############################## MODEL ####################################
model = model(args)
model.initialize_weights()
############################## LOGGER ###################################
save_dir = os.path.join(
args.default_root_dir,
args.experiment_name,
)
os.makedirs(save_dir, exist_ok=True)
wandb_logger = WandbLogger(
project=args.model,
name=args.experiment_name,
save_dir=save_dir,
)
wandb_logger.watch(model, log="all", log_freq=args.log_every_n_steps)
save_dir = wandb_logger.experiment.dir
############################## CALLBACKS ################################
callbacks = [
TQDMProgressBar(refresh_rate=5),
LearningRateMonitor(logging_interval="epoch"),
EarlyStopping(
monitor=args.callbacks_monitor,
mode=args.callbacks_mode,
min_delta=args.earlystooping_min_delta,
patience=args.earlystooping_patience,
verbose=args.callbacks_verbose,
),
ModelCheckpoint(
monitor=args.callbacks_monitor,
mode=args.callbacks_mode,
dirpath=os.path.join(save_dir, "ckpt"),
filename="[{epoch:04d}]-[{step:06d}]-[{val/acc:.4f}]",
auto_insert_metric_name=False,
save_top_k=args.callbacks_save_top_k,
save_last=True,
verbose=args.callbacks_verbose,
),
]
############################## TRAIN SETTING ############################
trainer = pl.Trainer.from_argparse_args(
args,
logger=wandb_logger,
callbacks=callbacks,
)
############################# TRAIN START ###############################
trainer.fit(model, datamodule=datamodule)
wandb_logger.experiment.unwatch(model)
############################# TEST START ###############################
test_info = trainer.test(model, datamodule=datamodule)
############################# MODEL SAVE ################################
example_inputs = torch.rand([1] + image_shape)
model.to_torchscript(
file_path=os.path.join(save_dir, "model.ts.zip"),
method="trace",
example_inputs=example_inputs,
)
model.to_onnx(
file_path=os.path.join(save_dir, "model.onnx"),
input_sample=example_inputs,
export_params=True,
input_names=["inputs"],
output_names=["output"],
)
return test_info
if __name__ == "__main__":
args = hyperparameters()
info = main(args)