forked from SIAnalytics/dual-hrnet
-
Notifications
You must be signed in to change notification settings - Fork 4
/
train_net.py
212 lines (167 loc) · 7.58 KB
/
train_net.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
import warnings
warnings.simplefilter("ignore", UserWarning)
import argparse
import multiprocessing
import os
import logging
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data.distributed import DistributedSampler
from torch.autograd import Variable
import torch.nn.functional as F
from yacs.config import CfgNode
from lovasz import lovasz_softmax
from models.dual_hrnet import get_model
from utils import AverageMeter, adjust_learning_rate
from xview2 import XView2Dataset
from utils import safe_mkdir
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', type=str, required=True, default="",
help='path the data folder')
parser.add_argument('--config_path', type=str, default="configs/dual-hrnet.yaml",
help='path of model config(ex:.yaml')
parser.add_argument("--ckpt_save_dir", type=str, default='ckpt/dual-hrnet/',
help='path to save checkpoints')
parser.add_argument('--test', type=str, required=False,
help='testing the model')
parser.add_argument("--local_rank", type=int, default=0)
args = parser.parse_args()
safe_mkdir(args.ckpt_save_dir)
logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
logger.addHandler(logging.FileHandler(os.path.join(args.ckpt_save_dir, 'train.log')))
logger.setLevel(level=logging.DEBUG)
class ModelLossWraper(nn.Module):
def __init__(self, model, class_weights=None, is_disaster_perd=False, is_split_loss=True):
super(ModelLossWraper, self).__init__()
if class_weights is None:
class_weights = []
self.model = model.cuda()
self.criterion = lovasz_softmax
self.weights = class_weights
self.is_disaster_pred = is_disaster_perd
self.is_split_loss = is_split_loss
def forward(self, inputs_pre, inputs_post, targets, target_disaster):
inputs_pre = Variable(inputs_pre).cuda()
inputs_post = Variable(inputs_post).cuda()
pred_dict = self.model(inputs_pre, inputs_post)
loc = F.softmax(pred_dict['loc'], dim=1)
loc = F.interpolate(loc, size=targets.size()[1:3], mode='bilinear')
if self.is_split_loss:
cls = F.softmax(pred_dict['cls'], dim=1)
cls = F.interpolate(cls, size=targets.size()[1:3], mode='bilinear')
targets[targets == 255] = -1
loc_targets = targets.clone()
loc_targets[loc_targets > 0] = 1
loc_targets[loc_targets < 0] = 255
loc_targets = Variable(loc_targets).cuda()
cls_targets = targets.clone()
cls_targets = cls_targets - 1
cls_targets[cls_targets < 0] = 255
cls_targets = Variable(cls_targets).cuda()
# loss = self.criterion(outputs, targets, ignore_label=255)
loc_loss = self.criterion(loc, loc_targets, ignore=255)
cls_loss = self.criterion(cls, cls_targets, ignore=255, weights=self.weights)
total_loss = loc_loss + cls_loss
else:
targets = Variable(targets).cuda()
total_loss = self.criterion(loc, targets, ignore=255, weights=self.weights)
if self.is_disaster_pred:
target_disaster = Variable(target_disaster).cuda()
disaster_loss = F.cross_entropy(pred_dict['disaster'], target_disaster)
total_loss += disaster_loss * 0.05
return total_loss
def main():
if args.config_path:
with open(args.config_path, 'rb') as fp:
config = CfgNode.load_cfg(fp)
else:
config = None
ckpts_save_dir = args.ckpt_save_dir
torch.backends.cudnn.deterministic = False
torch.backends.cudnn.benchmark = True
test_model = None
max_epoch = config.TRAIN.NUM_EPOCHS
if 'test' in args:
test_model = args.test
print('data folder: ', args.data_dir)
torch.backends.cudnn.benchmark = True
# WORLD_SIZE Generated by torch.distributed.launch.py
num_gpus = int(os.environ["WORLD_SIZE"]) if "WORLD_SIZE" in os.environ else 1
is_distributed = num_gpus > 1
if is_distributed:
torch.cuda.set_device(args.local_rank)
torch.distributed.init_process_group(
backend="nccl", init_method="env://",
)
model = get_model(config)
model_loss = ModelLossWraper(model,
config.TRAIN.CLASS_WEIGHTS,
config.MODEL.IS_DISASTER_PRED,
config.MODEL.IS_SPLIT_LOSS,
)
if is_distributed:
model_loss = nn.SyncBatchNorm.convert_sync_batchnorm(model_loss)
model_loss = nn.parallel.DistributedDataParallel(
model_loss, device_ids=[args.local_rank], output_device=args.local_rank
)
trainset = XView2Dataset(args.data_dir, rgb_bgr='rgb',
preprocessing={'flip': True,
'scale': config.TRAIN.MULTI_SCALE,
'crop': config.TRAIN.CROP_SIZE,
})
if is_distributed:
train_sampler = DistributedSampler(trainset)
else:
train_sampler = None
trainset_loader = torch.utils.data.DataLoader(trainset, batch_size=config.TRAIN.BATCH_SIZE_PER_GPU,
shuffle=train_sampler is None, pin_memory=True, drop_last=True,
sampler=train_sampler, num_workers=num_gpus)
model.train()
lr_init = config.TRAIN.LR
optimizer = torch.optim.SGD([{'params': filter(lambda p: p.requires_grad, model.parameters()), 'lr': lr_init}],
lr=lr_init,
momentum=0.9,
weight_decay=0.,
nesterov=False,
)
start_epoch = 0
losses = AverageMeter()
model.train()
num_iters = max_epoch * len(trainset_loader)
for epoch in range(start_epoch, max_epoch):
if is_distributed:
train_sampler.set_epoch(epoch)
cur_iters = epoch * len(trainset_loader)
for i, samples in enumerate(trainset_loader):
lr = adjust_learning_rate(optimizer, lr_init, num_iters, i + cur_iters)
inputs_pre = samples['pre_img']
inputs_post = samples['post_img']
target = samples['mask_img']
disaster_target = samples['disaster']
loss = model_loss(inputs_pre, inputs_post, target, disaster_target)
loss_sum = torch.sum(loss).detach().cpu()
if np.isnan(loss_sum) or np.isinf(loss_sum):
print('check')
losses.update(loss_sum, 4) # batch size
loss = torch.sum(loss)
loss.backward()
optimizer.step()
optimizer.zero_grad()
if args.local_rank == 0 and i % 10 == 0:
logger.info('epoch: {0}\t'
'iter: {1}/{2}\t'
'lr: {3:.6f}\t'
'loss: {loss.val:.4f} ({loss.ema:.4f})'.format(
epoch + 1, i + 1, len(trainset_loader), lr, loss=losses))
if args.local_rank == 0:
if (epoch + 1) % 50 == 0 and test_model is None:
torch.save({
'epoch': epoch + 1,
'state_dict': model.state_dict(),
'optimizer': optimizer.state_dict(),
}, os.path.join(ckpts_save_dir, 'hrnet_%s' % (epoch + 1)))
if __name__ == '__main__':
multiprocessing.set_start_method('spawn', True)
main()