forked from IDT-ITI/MMFusion-IML
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ws_train_phase2.py
196 lines (151 loc) · 7.31 KB
/
ws_train_phase2.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
"""
Created by Kostas Triaridis (@kostino)
in August 2023 @ ITI-CERTH
"""
import os
import argparse
import numpy as np
from tqdm import tqdm
from common.utils import AverageMeter
from common.losses import TruForLossPhase2
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DataLoader
import logging
import torch
import torchvision.transforms.functional as TF
from data.datasets import MixDataset
from common.metrics import computeDetectionMetrics
from model.ws_cmnext_conf import WSCMNeXtWithConf
from common.split_params import group_weight
from common.lr_schedule import WarmUpPolyLR
from model.modal_extract import ModalitiesExtractor
from configs.cmnext_init_cfg import _C as config, update_config
parser = argparse.ArgumentParser(description='')
parser.add_argument('-gpu', '--gpu', type=int, default=0, help='device, use -1 for cpu')
parser.add_argument('-log', '--log', type=str, default='INFO', help='logging level')
parser.add_argument('-exp', '--exp', type=str, default=None, help='Yaml experiment file')
parser.add_argument('-ckpt', '--ckpt', type=str, default=None, help='Localization checkpoint')
parser.add_argument('opts', help="other options", default=None, nargs=argparse.REMAINDER)
args = parser.parse_args()
config = update_config(config, args.exp)
gpu = args.gpu
loglvl = getattr(logging, args.log.upper())
logging.basicConfig(level=loglvl, format='%(message)s')
device = 'cuda:%d' % gpu if gpu >= 0 else 'cpu'
np.set_printoptions(formatter={'float': '{: 7.3f}'.format})
if device != 'cpu':
# cudnn setting
import torch.backends.cudnn as cudnn
cudnn.benchmark = config.CUDNN.BENCHMARK
cudnn.deterministic = config.CUDNN.DETERMINISTIC
cudnn.enabled = config.CUDNN.ENABLED
modal_extractor = ModalitiesExtractor(config.MODEL.MODALS[1:], config.MODEL.NP_WEIGHTS)
model = WSCMNeXtWithConf(config.MODEL)
ckpt = torch.load(args.ckpt)
model.load_state_dict(ckpt['state_dict'], strict=False)
modal_extractor.load_state_dict(ckpt['extractor_state_dict'])
modal_extractor.to(device)
model = model.to(device)
train = MixDataset(config.DATASET.TRAIN,
config.DATASET.IMG_SIZE,
train=True,
class_weight=config.DATASET.CLASS_WEIGHTS)
val = MixDataset(config.DATASET.VAL,
config.DATASET.IMG_SIZE,
train=False)
logging.info(train.get_info())
train_loader = DataLoader(train,
batch_size=config.BATCH_SIZE,
shuffle=True,
num_workers=config.WORKERS,
pin_memory=True)
val_loader = DataLoader(val,
batch_size=1,
shuffle=False,
num_workers=config.WORKERS,
pin_memory=True)
criterion = TruForLossPhase2()
os.makedirs('./ckpt/{}'.format(config.MODEL.NAME), exist_ok=True)
logdir = './{}/{}'.format(config.LOG_DIR, config.MODEL.NAME)
os.makedirs(logdir, exist_ok=True)
writer = SummaryWriter('./{}/{}'.format(config.LOG_DIR, config.MODEL.NAME))
cmnext_params = []
cmnext_params = group_weight(cmnext_params, model, torch.nn.BatchNorm2d, config.LEARNING_RATE)
params = cmnext_params
optimizer = torch.optim.SGD(params,
lr=config.LEARNING_RATE,
momentum=config.SGD_MOMENTUM,
weight_decay=config.WD
)
iters_per_epoch = len(train_loader)
iters = 0
max_iters = config.EPOCHS * iters_per_epoch
min_loss = 100
lr_schedule = WarmUpPolyLR(optimizer,
start_lr=config.LEARNING_RATE,
lr_power=0.9,
total_iters=max_iters,
warmup_steps=iters_per_epoch * config.WARMUP_EPOCHS)
scaler = torch.cuda.amp.GradScaler()
for epoch in range(config.EPOCHS):
train.shuffle() # for balanced sampling
model.set_train()
modal_extractor.set_val()
avg_loss = AverageMeter()
optimizer.zero_grad(set_to_none=True)
pbar = tqdm(train_loader, desc='Training Epoch {}/{}'.format(epoch + 1, config.EPOCHS), unit='steps')
for step, (images, _, masks, labels) in enumerate(pbar):
images = images.to(device, non_blocking=True)
labels = labels.to(device, non_blocking=True)
masks = masks.squeeze(1).to(device, non_blocking=True)
with torch.autocast(device_type='cuda', dtype=torch.float16):
modals = modal_extractor(images)
images_norm = TF.normalize(images, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
inp = [images_norm] + modals
anomaly, confidence, detection = model(inp)
loss = criterion(anomaly, masks, confidence, detection, labels) / config.ACCUMULATE_ITERS
scaler.scale(loss).backward()
if ((step + 1) % config.ACCUMULATE_ITERS == 0) or (step + 1 == len(train_loader)):
scaler.step(optimizer)
scaler.update()
optimizer.zero_grad(set_to_none=True)
avg_loss.update(loss.detach().item())
curr_iters = epoch * iters_per_epoch + step
lr_schedule.step(cur_iter=curr_iters)
writer.add_scalar('Total Loss', loss.detach().item(), curr_iters)
writer.add_scalar('Learning Rate', optimizer.param_groups[0]['lr'], curr_iters)
pbar.set_postfix({"last_loss": loss.detach().item(), "epoch_loss": avg_loss.average()})
scores = []
labels = []
val_loss_avg = AverageMeter()
model.set_val()
modal_extractor.set_val()
pbar = tqdm(val_loader, desc='Validating Epoch {}/{}'.format(epoch + 1, config.EPOCHS), unit='steps')
for step, (images, _, masks, lab) in enumerate(pbar):
with torch.no_grad():
images = images.to(device, non_blocking=True)
lab = lab.to(device, non_blocking=True)
masks = masks.squeeze(1).to(device, non_blocking=True)
with torch.autocast(device_type='cuda', dtype=torch.float16):
modals = modal_extractor(images)
images_norm = TF.normalize(images, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
inp = [images_norm] + modals
anomaly, confidence, detection = model(inp)
val_loss = criterion(anomaly, masks, confidence, detection, lab)
val_loss_avg.update(val_loss.detach().item())
scores.append(detection.squeeze().detach().cpu().item())
labels.append(lab.squeeze().detach().cpu().item())
auc, baCC = computeDetectionMetrics(scores, labels)
writer.add_scalar('Val Loss', val_loss_avg.average(), epoch)
writer.add_scalar('Val AUC', auc, epoch)
writer.add_scalar('Val bACC', baCC, epoch)
if val_loss_avg.average() < min_loss:
min_loss = val_loss_avg.average()
result = {'epoch': epoch, 'val_loss': val_loss_avg.average(),'val_baCC': baCC,
'val_auc': auc, 'state_dict': model.state_dict(),
'extractor_state_dict': modal_extractor.state_dict()}
torch.save(result, './ckpt/{}/best_val_loss.pth'.format(config.MODEL.NAME))
result = {'epoch': config.EPOCHS - 1, 'val_loss': val_loss_avg.average(), 'val_baCC': baCC,
'val_auc': auc, 'state_dict': model.state_dict(),
'extractor_state_dict': modal_extractor.state_dict()}
torch.save(result, './ckpt/{}/final.pth'.format(config.MODEL.NAME))