-
Notifications
You must be signed in to change notification settings - Fork 9
/
train_baseline_semi.py
210 lines (161 loc) · 8.2 KB
/
train_baseline_semi.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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import argparse
import logging
import os
import pprint
import numpy as np
import torch
from torch import nn
import torch.backends.cudnn as cudnn
from torch.optim import SGD
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import yaml
from dataset.semi import SemiDataset
from train_baseline_sup import evaluate
from util.classes import CLASSES
from util.ohem import ProbOhemCrossEntropy2d
from util.utils import count_params, init_log, AverageMeter
from util.dist_helper import setup_distributed
from model.model_helper import ModelBuilder
parser = argparse.ArgumentParser(description='Revisiting Weak-to-Strong Consistency in Semi-Supervised Semantic Segmentation')
parser.add_argument('--config', type=str, required=True)
parser.add_argument('--labeled-id-path', type=str, required=True)
parser.add_argument('--unlabeled-id-path', type=str, required=True)
parser.add_argument('--save-path', type=str, required=True)
parser.add_argument('--local_rank', default=0, type=int)
parser.add_argument('--port', default=None, type=int)
parser.add_argument('--seed', default=114154, type=int)
def main():
args = parser.parse_args()
import random
SEED=args.seed
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
torch.cuda.manual_seed_all(SEED)
cfg = yaml.load(open(args.config, "r"), Loader=yaml.Loader)
logger = init_log('global', logging.INFO)
logger.propagate = 0
rank, world_size = setup_distributed(port=args.port)
if rank == 0:
all_args = {**cfg, **vars(args), 'ngpus': world_size}
logger.info('{}\n'.format(pprint.pformat(all_args)))
writer = SummaryWriter(args.save_path)
os.makedirs(args.save_path, exist_ok=True)
cudnn.enabled = True
cudnn.benchmark = True
model = ModelBuilder(cfg['model'])
optimizer = SGD([{'params': model.backbone.parameters(), 'lr': cfg['lr']},
{'params': [param for name, param in model.named_parameters() if 'backbone' not in name],
'lr': cfg['lr'] * cfg['lr_multi']}], lr=cfg['lr'], momentum=0.9, weight_decay=1e-4)
if rank == 0:
logger.info('Total params: {:.1f}M\n'.format(count_params(model)))
local_rank = int(os.environ["LOCAL_RANK"])
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)
model.cuda()
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[local_rank],
output_device=local_rank, find_unused_parameters=False)
if cfg['criterion']['name'] == 'CELoss':
criterion_l = nn.CrossEntropyLoss(**cfg['criterion']['kwargs']).cuda(local_rank)
elif cfg['criterion']['name'] == 'OHEM':
criterion_l = ProbOhemCrossEntropy2d(**cfg['criterion']['kwargs']).cuda(local_rank)
else:
raise NotImplementedError('%s criterion is not implemented' % cfg['criterion']['name'])
criterion_u = nn.CrossEntropyLoss(**cfg['criterion']['kwargs']).cuda(local_rank)
trainset_u = SemiDataset(cfg['dataset'], cfg['data_root'], 'train_u',
cfg['crop_size'], args.unlabeled_id_path)
trainset_l = SemiDataset(cfg['dataset'], cfg['data_root'], 'train_l',
cfg['crop_size'], args.labeled_id_path, nsample=len(trainset_u.ids))
valset = SemiDataset(cfg['dataset'], cfg['data_root'], 'val')
trainsampler_l = torch.utils.data.distributed.DistributedSampler(trainset_l)
trainloader_l = DataLoader(trainset_l, batch_size=cfg['batch_size'],
pin_memory=True, num_workers=1, drop_last=True, sampler=trainsampler_l)
trainsampler_u = torch.utils.data.distributed.DistributedSampler(trainset_u)
trainloader_u = DataLoader(trainset_u, batch_size=cfg['batch_size'],
pin_memory=True, num_workers=1, drop_last=True, sampler=trainsampler_u)
valsampler = torch.utils.data.distributed.DistributedSampler(valset)
valloader = DataLoader(valset, batch_size=1, pin_memory=True, num_workers=1,
drop_last=False, sampler=valsampler)
total_iters = len(trainloader_u) * cfg['epochs']
previous_best = 0.0
best_epoch = 0
epoch = -1
if os.path.exists(os.path.join(args.save_path, 'latest.pth')):
checkpoint = torch.load(os.path.join(args.save_path, 'latest.pth'))
model.load_state_dict(checkpoint['model'])
optimizer.load_state_dict(checkpoint['optimizer'])
epoch = checkpoint['epoch']
best_epoch = checkpoint['best_epoch']
previous_best = checkpoint['previous_best']
if rank == 0:
logger.info('************ Load from checkpoint at epoch %i\n' % epoch)
for epoch in range(epoch + 1, cfg['epochs']):
if rank == 0:
logger.info('===========> Epoch: {:}, LR: {:.5f}, Previous best: {:.2f} in Epoch {:}'.format(
epoch, optimizer.param_groups[0]['lr'], previous_best, best_epoch))
total_loss = AverageMeter()
total_loss_x = AverageMeter()
total_loss_w_fp = AverageMeter()
trainloader_l.sampler.set_epoch(epoch)
trainloader_u.sampler.set_epoch(epoch)
loader = zip(trainloader_l, trainloader_u)
for i, ((img_x, mask_x), img_u_s) in enumerate(loader):
img_x, mask_x = img_x.cuda(), mask_x.cuda()
img_u_s = img_u_s.cuda()
with torch.no_grad():
model.eval()
pred_u_pseudo = model(img_u_s).detach()
pseudo_label = pred_u_pseudo.argmax(dim=1)
model.train()
num_lb, num_ulb = img_x.shape[0], img_u_s.shape[0]
preds = model(torch.cat((img_x, img_u_s)))
pred_x, pred_u = preds.split([num_lb, num_ulb])
loss_x = criterion_l(pred_x, mask_x)
loss_u_w_fp = criterion_u(pred_u, pseudo_label)
loss = (loss_x + loss_u_w_fp) / 2.0
torch.distributed.barrier()
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_loss.update(loss.item())
total_loss_x.update(loss_x.item())
total_loss_w_fp.update(loss_u_w_fp.item())
iters = epoch * len(trainloader_u) + i
lr = cfg['lr'] * (1 - iters / total_iters) ** 0.9
optimizer.param_groups[0]["lr"] = lr
optimizer.param_groups[1]["lr"] = lr * cfg['lr_multi']
if rank == 0:
writer.add_scalar('train/loss_all', loss.item(), iters)
writer.add_scalar('train/loss_x', loss_x.item(), iters)
writer.add_scalar('train/loss_w_fp', loss_u_w_fp.item(), iters)
if (i % (len(trainloader_u) // 8) == 0) and (rank == 0):
logger.info('Iters: {:}, Total loss: {:.3f}, Loss x: {:.3f}, Loss w_fp: {:.3f}'
.format(i, total_loss.avg, total_loss_x.avg, total_loss_w_fp.avg))
eval_mode = 'sliding_window' if cfg['dataset'] == 'cityscapes' else 'original'
mIoU, iou_class = evaluate(model, valloader, eval_mode, cfg)
if rank == 0:
for (cls_idx, iou) in enumerate(iou_class):
logger.info('***** Evaluation ***** >>>> Class [{:} {:}] '
'IoU: {:.2f}'.format(cls_idx, CLASSES[cfg['dataset']][cls_idx], iou))
logger.info('***** Evaluation {} ***** >>>> MeanIoU: {:.2f}\n'.format(eval_mode, mIoU))
writer.add_scalar('eval/mIoU', mIoU, epoch)
for i, iou in enumerate(iou_class):
writer.add_scalar('eval/%s_IoU' % (CLASSES[cfg['dataset']][i]), iou, epoch)
is_best = mIoU > previous_best
previous_best = max(mIoU, previous_best)
if is_best:
best_epoch = epoch
if rank == 0:
checkpoint = {
'model': model.state_dict(),
'optimizer': optimizer.state_dict(),
'epoch': epoch,
'best_epoch': best_epoch,
'previous_best': previous_best,
}
torch.save(checkpoint, os.path.join(args.save_path, 'latest.pth'))
if is_best:
torch.save(checkpoint, os.path.join(args.save_path, 'best.pth'))
if __name__ == '__main__':
main()