forked from zhulf0804/PointPillars
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
248 lines (213 loc) · 12.2 KB
/
train.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
244
245
246
247
248
import argparse
import os
import torch
from tqdm import tqdm
import pdb
from utils import setup_seed
from dataset import Kitti, get_dataloader
from model import PointPillars
from loss import Loss
# from torch.utils.tensorboard import SummaryWriter
import wandb
# def save_summary(writer, loss_dict, global_step, tag, lr=None, momentum=None):
# for k, v in loss_dict.items():
# writer.add_scalar(f'{tag}/{k}', v, global_step)
# if lr is not None:
# writer.add_scalar('lr', lr, global_step)
# if momentum is not None:
# writer.add_scalar('momentum', momentum, global_step)
def save_summary(loss_dict, global_step, tag, lr=None, momentum=None):
log_dict = {f'{tag}/{k}': v for k, v in loss_dict.items()}
log_dict['global_step'] = global_step
if lr is not None:
log_dict['lr'] = lr
if momentum is not None:
log_dict['momentum'] = momentum
wandb.log(log_dict, step=global_step)
def main(args):
wandb.init(project="PointPillars 3D Object Detection", config=args)
setup_seed()
train_dataset = Kitti(data_root=args.data_root,
split='train')
val_dataset = Kitti(data_root=args.data_root,
split='val')
train_dataloader = get_dataloader(dataset=train_dataset,
batch_size=args.batch_size,
num_workers=args.num_workers,
shuffle=True)
val_dataloader = get_dataloader(dataset=val_dataset,
batch_size=args.batch_size,
num_workers=args.num_workers,
shuffle=False)
if not args.no_cuda:
pointpillars = PointPillars(nclasses=args.nclasses).cuda()
else:
pointpillars = PointPillars(nclasses=args.nclasses)
loss_func = Loss()
max_iters = len(train_dataloader) * args.max_epoch
init_lr = args.init_lr
optimizer = torch.optim.AdamW(params=pointpillars.parameters(),
lr=init_lr,
betas=(0.95, 0.99),
weight_decay=0.01)
scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer,
max_lr=init_lr*10,
total_steps=max_iters,
pct_start=0.4,
anneal_strategy='cos',
cycle_momentum=True,
base_momentum=0.95*0.895,
max_momentum=0.95,
div_factor=10)
# saved_logs_path = os.path.join(args.saved_path, 'summary')
# os.makedirs(saved_logs_path, exist_ok=True)
# writer = SummaryWriter(saved_logs_path)
saved_ckpt_path = os.path.join(args.saved_path, 'checkpoints')
os.makedirs(saved_ckpt_path, exist_ok=True)
for epoch in range(args.max_epoch):
print('=' * 20, epoch, '=' * 20)
train_step, val_step = 0, 0
# Initialize loss accumulators
train_loss_dict = {'total_loss': 0, 'cls_loss': 0, 'reg_loss': 0, 'dir_cls_loss': 0}
train_batches = 0
for i, data_dict in enumerate(tqdm(train_dataloader)):
if not args.no_cuda:
# move the tensors to the cuda
for key in data_dict:
for j, item in enumerate(data_dict[key]):
if torch.is_tensor(item):
data_dict[key][j] = data_dict[key][j].cuda()
optimizer.zero_grad()
batched_pts = data_dict['batched_pts']
batched_gt_bboxes = data_dict['batched_gt_bboxes']
batched_labels = data_dict['batched_labels']
batched_difficulty = data_dict['batched_difficulty']
bbox_cls_pred, bbox_pred, bbox_dir_cls_pred, anchor_target_dict = \
pointpillars(batched_pts=batched_pts,
mode='train',
batched_gt_bboxes=batched_gt_bboxes,
batched_gt_labels=batched_labels)
bbox_cls_pred = bbox_cls_pred.permute(0, 2, 3, 1).reshape(-1, args.nclasses)
bbox_pred = bbox_pred.permute(0, 2, 3, 1).reshape(-1, 7)
bbox_dir_cls_pred = bbox_dir_cls_pred.permute(0, 2, 3, 1).reshape(-1, 2)
batched_bbox_labels = anchor_target_dict['batched_labels'].reshape(-1)
batched_label_weights = anchor_target_dict['batched_label_weights'].reshape(-1)
batched_bbox_reg = anchor_target_dict['batched_bbox_reg'].reshape(-1, 7)
# batched_bbox_reg_weights = anchor_target_dict['batched_bbox_reg_weights'].reshape(-1)
batched_dir_labels = anchor_target_dict['batched_dir_labels'].reshape(-1)
# batched_dir_labels_weights = anchor_target_dict['batched_dir_labels_weights'].reshape(-1)
pos_idx = (batched_bbox_labels >= 0) & (batched_bbox_labels < args.nclasses)
bbox_pred = bbox_pred[pos_idx]
batched_bbox_reg = batched_bbox_reg[pos_idx]
# sin(a - b) = sin(a)*cos(b) - cos(a)*sin(b)
bbox_pred[:, -1] = torch.sin(bbox_pred[:, -1].clone()) * torch.cos(batched_bbox_reg[:, -1].clone())
batched_bbox_reg[:, -1] = torch.cos(bbox_pred[:, -1].clone()) * torch.sin(batched_bbox_reg[:, -1].clone())
bbox_dir_cls_pred = bbox_dir_cls_pred[pos_idx]
batched_dir_labels = batched_dir_labels[pos_idx]
num_cls_pos = (batched_bbox_labels < args.nclasses).sum()
bbox_cls_pred = bbox_cls_pred[batched_label_weights > 0]
batched_bbox_labels[batched_bbox_labels < 0] = args.nclasses
batched_bbox_labels = batched_bbox_labels[batched_label_weights > 0]
loss_dict = loss_func(bbox_cls_pred=bbox_cls_pred,
bbox_pred=bbox_pred,
bbox_dir_cls_pred=bbox_dir_cls_pred,
batched_labels=batched_bbox_labels,
num_cls_pos=num_cls_pos,
batched_bbox_reg=batched_bbox_reg,
batched_dir_labels=batched_dir_labels)
loss = loss_dict['total_loss']
loss.backward()
# torch.nn.utils.clip_grad_norm_(pointpillars.parameters(), max_norm=35)
optimizer.step()
scheduler.step()
# Accumulate losses
for key in train_loss_dict:
train_loss_dict[key] += loss_dict[key].item()
train_batches += 1
train_step += 1
for key in train_loss_dict:
train_loss_dict[key] /= train_batches
save_summary(train_loss_dict, epoch + 1, 'train', lr=optimizer.param_groups[0]['lr'], momentum=optimizer.param_groups[0]['betas'][0])
if (epoch + 1) % args.ckpt_freq_epoch == 0:
torch.save(pointpillars.state_dict(), os.path.join(saved_ckpt_path, f'epoch_{epoch+1}.pth'))
# if epoch % 2 == 0:
# continue
pointpillars.eval()
val_loss_dict = {'total_loss': 0, 'cls_loss': 0, 'reg_loss': 0, 'dir_cls_loss': 0}
val_batches = 0
with torch.no_grad():
for i, data_dict in enumerate(tqdm(val_dataloader)):
if not args.no_cuda:
# move the tensors to the cuda
for key in data_dict:
for j, item in enumerate(data_dict[key]):
if torch.is_tensor(item):
data_dict[key][j] = data_dict[key][j].cuda()
batched_pts = data_dict['batched_pts']
batched_gt_bboxes = data_dict['batched_gt_bboxes']
batched_labels = data_dict['batched_labels']
batched_difficulty = data_dict['batched_difficulty']
bbox_cls_pred, bbox_pred, bbox_dir_cls_pred, anchor_target_dict = \
pointpillars(batched_pts=batched_pts,
mode='train',
batched_gt_bboxes=batched_gt_bboxes,
batched_gt_labels=batched_labels)
bbox_cls_pred = bbox_cls_pred.permute(0, 2, 3, 1).reshape(-1, args.nclasses)
bbox_pred = bbox_pred.permute(0, 2, 3, 1).reshape(-1, 7)
bbox_dir_cls_pred = bbox_dir_cls_pred.permute(0, 2, 3, 1).reshape(-1, 2)
batched_bbox_labels = anchor_target_dict['batched_labels'].reshape(-1)
batched_label_weights = anchor_target_dict['batched_label_weights'].reshape(-1)
batched_bbox_reg = anchor_target_dict['batched_bbox_reg'].reshape(-1, 7)
# batched_bbox_reg_weights = anchor_target_dict['batched_bbox_reg_weights'].reshape(-1)
batched_dir_labels = anchor_target_dict['batched_dir_labels'].reshape(-1)
# batched_dir_labels_weights = anchor_target_dict['batched_dir_labels_weights'].reshape(-1)
pos_idx = (batched_bbox_labels >= 0) & (batched_bbox_labels < args.nclasses)
bbox_pred = bbox_pred[pos_idx]
batched_bbox_reg = batched_bbox_reg[pos_idx]
# sin(a - b) = sin(a)*cos(b) - cos(a)*sin(b)
bbox_pred[:, -1] = torch.sin(bbox_pred[:, -1]) * torch.cos(batched_bbox_reg[:, -1])
batched_bbox_reg[:, -1] = torch.cos(bbox_pred[:, -1]) * torch.sin(batched_bbox_reg[:, -1])
bbox_dir_cls_pred = bbox_dir_cls_pred[pos_idx]
batched_dir_labels = batched_dir_labels[pos_idx]
num_cls_pos = (batched_bbox_labels < args.nclasses).sum()
bbox_cls_pred = bbox_cls_pred[batched_label_weights > 0]
batched_bbox_labels[batched_bbox_labels < 0] = args.nclasses
batched_bbox_labels = batched_bbox_labels[batched_label_weights > 0]
loss_dict = loss_func(bbox_cls_pred=bbox_cls_pred,
bbox_pred=bbox_pred,
bbox_dir_cls_pred=bbox_dir_cls_pred,
batched_labels=batched_bbox_labels,
num_cls_pos=num_cls_pos,
batched_bbox_reg=batched_bbox_reg,
batched_dir_labels=batched_dir_labels)
# Accumulate losses
for key in val_loss_dict:
val_loss_dict[key] += loss_dict[key]
val_batches += 1
# global_step = epoch * len(val_dataloader) + val_step + 1
# if global_step % args.log_freq == 0:
# # save_summary(writer, loss_dict, global_step, 'val')
# save_summary(loss_dict, global_step, 'val')
# val_step += 1
# Average the validation losses
for key in val_loss_dict:
val_loss_dict[key] /= val_batches
# Log the averaged validation losses
save_summary(val_loss_dict, epoch + 1, 'val')
pointpillars.train()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Configuration Parameters')
parser.add_argument('--data_root', default='/mnt/ssd1/lifa_rdata/det/kitti',
help='your data root for kitti')
parser.add_argument('--saved_path', default='pillar_logs')
parser.add_argument('--batch_size', type=int, default=6)
parser.add_argument('--num_workers', type=int, default=4)
parser.add_argument('--nclasses', type=int, default=3)
parser.add_argument('--init_lr', type=float, default=0.00025)
parser.add_argument('--max_epoch', type=int, default=160)
parser.add_argument('--log_freq', type=int, default=8)
parser.add_argument('--ckpt_freq_epoch', type=int, default=20)
parser.add_argument('--no_cuda', action='store_true',
help='whether to use cuda')
args = parser.parse_args()
main(args)