-
Notifications
You must be signed in to change notification settings - Fork 20
/
train_source_free.py
executable file
·243 lines (196 loc) · 8.83 KB
/
train_source_free.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import argparse
import os
import datetime
import logging
import time
import torch
import torch.nn as nn
import torch.utils
import torch.distributed
from torch.utils.data import DataLoader
from core.configs import cfg
from core.datasets import build_dataset
from core.models import build_feature_extractor, build_classifier
from core.solver import adjust_learning_rate
from core.utils.misc import mkdir
from core.utils.logger import setup_logger
from core.utils.metric_logger import MetricLogger
from core.active.build import PixelSelection, RegionSelection
from core.datasets.dataset_path_catalog import DatasetCatalog
from core.loss.negative_learning_loss import NegativeLearningLoss
from core.utils.utils import set_random_seed
import setproctitle
import warnings
warnings.filterwarnings('ignore')
def train(cfg):
logger = logging.getLogger("AL-RIPU.trainer")
# create network
device = torch.device(cfg.MODEL.DEVICE)
feature_extractor = build_feature_extractor(cfg)
feature_extractor.to(device)
classifier = build_classifier(cfg)
classifier.to(device)
print(classifier)
# init optimizer
optimizer_fea = torch.optim.SGD(feature_extractor.parameters(), lr=cfg.SOLVER.BASE_LR, momentum=cfg.SOLVER.MOMENTUM,
weight_decay=cfg.SOLVER.WEIGHT_DECAY)
optimizer_fea.zero_grad()
optimizer_cls = torch.optim.SGD(classifier.parameters(), lr=cfg.SOLVER.BASE_LR * 10, momentum=cfg.SOLVER.MOMENTUM,
weight_decay=cfg.SOLVER.WEIGHT_DECAY)
optimizer_cls.zero_grad()
# load checkpoint
if cfg.resume:
logger.info("Loading checkpoint from {}".format(cfg.resume))
checkpoint = torch.load(cfg.resume, map_location=torch.device('cpu'))
feature_extractor.load_state_dict(checkpoint['feature_extractor'])
classifier.load_state_dict(checkpoint['classifier'])
else:
print("please set the source only model path 'cfg.resume'!")
return
# init mask for cityscape
DatasetCatalog.initMask(cfg)
# init data loader
tgt_train_data = build_dataset(cfg, mode='train', is_source=False)
tgt_epoch_data = build_dataset(cfg, mode='active', is_source=False, epochwise=True)
tgt_train_loader = DataLoader(tgt_train_data, batch_size=cfg.SOLVER.BATCH_SIZE, shuffle=True, num_workers=4,
pin_memory=True, drop_last=True)
tgt_epoch_loader = DataLoader(tgt_epoch_data, batch_size=1, shuffle=False, num_workers=4,
pin_memory=True, drop_last=False)
# init loss
sup_criterion = nn.CrossEntropyLoss(ignore_index=255)
negative_criterion = NegativeLearningLoss()
iteration = 0
start_training_time = time.time()
end = time.time()
max_iters = cfg.SOLVER.MAX_ITER
meters = MetricLogger(delimiter=" ")
logger.info(">>>>>>>>>>>>>>>> Start Training >>>>>>>>>>>>>>>>")
feature_extractor.train()
classifier.train()
active_round = 1
for batch_index, tgt_data in enumerate(tgt_train_loader):
data_time = time.time() - end
# source free active da, active at first
if iteration in cfg.ACTIVE.SELECT_ITER:
if cfg.ACTIVE.SETTING == "RA":
RegionSelection(cfg=cfg,
feature_extractor=feature_extractor,
classifier=classifier,
tgt_epoch_loader=tgt_epoch_loader)
elif cfg.ACTIVE.SETTING == 'PA':
PixelSelection(cfg=cfg,
feature_extractor=feature_extractor,
classifier=classifier,
tgt_epoch_loader=tgt_epoch_loader)
active_round += 1
current_lr = adjust_learning_rate(cfg.SOLVER.LR_METHOD, cfg.SOLVER.BASE_LR, iteration, max_iters,
power=cfg.SOLVER.LR_POWER)
for index in range(len(optimizer_fea.param_groups)):
optimizer_fea.param_groups[index]['lr'] = current_lr
for index in range(len(optimizer_cls.param_groups)):
optimizer_cls.param_groups[index]['lr'] = current_lr * 10
optimizer_fea.zero_grad()
optimizer_cls.zero_grad()
# target data
# tgt_mask is active label, 255 means unlabeled data
tgt_input, tgt_mask = tgt_data['img'], tgt_data['mask']
tgt_input = tgt_input.cuda(non_blocking=True)
tgt_mask = tgt_mask.cuda(non_blocking=True)
tgt_size = tgt_input.shape[-2:]
tgt_out = classifier(feature_extractor(tgt_input), size=tgt_size)
predict = torch.softmax(tgt_out, dim=1)
loss = torch.Tensor([0]).cuda()
# target active supervision loss
if torch.sum((tgt_mask != 255)) != 0: # target has labeled pixels
loss_sup_tgt = sup_criterion(tgt_out, tgt_mask)
meters.update(loss_sup_tgt=loss_sup_tgt.item())
loss += loss_sup_tgt
# target negative pseudo loss
if cfg.SOLVER.NEGATIVE_LOSS > 0:
negative_learning_loss = negative_criterion(predict) * cfg.SOLVER.NEGATIVE_LOSS
meters.update(negative_pseudo_loss=negative_learning_loss.item())
loss += negative_learning_loss
loss.backward()
optimizer_fea.step()
optimizer_cls.step()
batch_time = time.time() - end
end = time.time()
meters.update(time=batch_time, data=data_time)
eta_seconds = meters.time.global_avg * (cfg.SOLVER.STOP_ITER - iteration)
eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
iteration += 1
if iteration % 20 == 0 or iteration == max_iters:
logger.info(
meters.delimiter.join(
[
"eta: {eta}",
"iter: {iter}",
"{meters}",
"lr: {lr:.6f}",
"max mem: {memory:.02f} GB"
]
).format(
eta=eta_string,
iter=iteration,
meters=str(meters),
lr=optimizer_fea.param_groups[0]["lr"],
memory=torch.cuda.max_memory_allocated() / 1024.0 / 1024.0 / 1024.0
)
)
if iteration == cfg.SOLVER.MAX_ITER or iteration % cfg.SOLVER.CHECKPOINT_PERIOD == 0:
filename = os.path.join(cfg.OUTPUT_DIR, "model_iter{:06d}.pth".format(iteration))
torch.save({'iteration': iteration,
'feature_extractor': feature_extractor.state_dict(),
'classifier': classifier.state_dict(),
'optimizer_fea': optimizer_fea.state_dict(),
'optimizer_cls': optimizer_cls.state_dict(),
}, filename)
if iteration == cfg.SOLVER.MAX_ITER:
break
if iteration == cfg.SOLVER.STOP_ITER:
break
total_training_time = time.time() - start_training_time
total_time_str = str(datetime.timedelta(seconds=total_training_time))
logger.info(
"Total training time: {} ({:.4f} s / it)".format(
total_time_str, total_training_time / cfg.SOLVER.STOP_ITER
)
)
def main():
parser = argparse.ArgumentParser(description="Active Domain Adaptive Semantic Segmentation Training")
parser.add_argument("-cfg",
"--config-file",
default="",
metavar="FILE",
help="path to config file",
type=str)
parser.add_argument("--proctitle",
type=str,
default="AL-RIPU",
help="allow a process to change its title", )
parser.add_argument(
"opts",
help="Modify config options using the command-line",
default=None,
nargs=argparse.REMAINDER
)
args = parser.parse_args()
if args.opts is not None:
args.opts[-1] = args.opts[-1].strip('\r\n')
torch.backends.cudnn.benchmark = True
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
cfg.freeze()
output_dir = cfg.OUTPUT_DIR
if output_dir:
mkdir(output_dir)
setproctitle.setproctitle(f'{args.proctitle}')
logger = setup_logger("AL-RIPU", output_dir, 0)
logger.info(args)
logger.info("Loaded configuration file {}".format(args.config_file))
logger.info("Running with config:\n{}".format(cfg))
logger.info('Initializing Cityscapes label mask...')
set_random_seed(cfg.SEED)
train(cfg)
if __name__ == '__main__':
main()