-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_learn_multiscene_pose_encoding.py
234 lines (187 loc) · 9.94 KB
/
main_learn_multiscene_pose_encoding.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
import argparse
import torch
import numpy as np
import json
import logging
from util import utils
import time
from datasets.CameraPoseDataset import CameraPoseDataset
from models.pose_losses import CameraPoseLoss
from models.pose_regressors import get_model
from os.path import join
from models.pose_encoder import MultiSCenePoseEncoder
if __name__ == "__main__":
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("model_name",
help="name of model to create (e.g. posenet, transposenet")
arg_parser.add_argument("mode", help="train or eval")
arg_parser.add_argument("backbone_path", help="path to backbone .pth - e.g. efficientnet")
arg_parser.add_argument("dataset_path", help="path to the physical location of the dataset")
arg_parser.add_argument("labels_file", help="path to a file mapping images to their poses")
arg_parser.add_argument("config_file", help="path to configuration file", default="7scenes-config.json")
arg_parser.add_argument("checkpoint_path",
help="path to a pre-trained model (should match the model indicated in model_name")
arg_parser.add_argument("--encoder_checkpoint_path", help="path to a trained pose encoder")
arg_parser.add_argument("--experiment", help="a short string to describe the experiment/commit used")
args = arg_parser.parse_args()
utils.init_logger()
# Record execution details
logging.info("Start {} with {}".format(args.model_name, args.mode))
if args.experiment is not None:
logging.info("Experiment details: {}".format(args.experiment))
logging.info("Using dataset: {}".format(args.dataset_path))
logging.info("Using labels file: {}".format(args.labels_file))
# Read configuration
with open(args.config_file, "r") as read_file:
config = json.load(read_file)
model_params = config[args.model_name]
general_params = config['general']
config = {**model_params, **general_params}
logging.info("Running with configuration:\n{}".format(
'\n'.join(["\t{}: {}".format(k, v) for k, v in config.items()])))
# Set the seeds and the device
use_cuda = torch.cuda.is_available()
device_id = 'cpu'
torch_seed = 0
numpy_seed = 2
torch.manual_seed(torch_seed)
if use_cuda:
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
device_id = config.get('device_id')
np.random.seed(numpy_seed)
device = torch.device(device_id)
# Load the apr model
apr = get_model(args.model_name, args.backbone_path, config).to(device)
apr.load_state_dict(torch.load(args.checkpoint_path, map_location=device_id))
logging.info("Initializing from checkpoint: {}".format(args.checkpoint_path))
apr.eval()
pose_encoder = MultiSCenePoseEncoder(config.get("hidden_dim")).to(device)
print(pose_encoder)
if args.encoder_checkpoint_path:
pose_encoder.load_state_dict(torch.load(args.encoder_checkpoint_path, map_location=device_id))
logging.info("Initializing encoder from checkpoint: {}".format(args.encoder_checkpoint_path))
if args.mode == 'train':
# Set to train mode
pose_encoder.train()
# Set the losses
pose_loss = CameraPoseLoss(config).to(device)
mse_loss = torch.nn.MSELoss()
# Set the optimizer and scheduler
params = list(pose_encoder.parameters()) + list(pose_loss.parameters())
optim = torch.optim.Adam(filter(lambda p: p.requires_grad, params),
lr=config.get('lr'),
eps=config.get('eps'),
weight_decay=config.get('weight_decay'))
scheduler = torch.optim.lr_scheduler.StepLR(optim,
step_size=config.get('lr_scheduler_step_size'),
gamma=config.get('lr_scheduler_gamma'))
transform = utils.test_transforms.get('baseline')
dataset = CameraPoseDataset(args.dataset_path, args.labels_file, transform, False)
loader_params = {'batch_size': config.get('batch_size'),
'shuffle': True,
'num_workers': config.get('n_workers')}
dataloader = torch.utils.data.DataLoader(dataset, **loader_params)
# Get training details
n_freq_print = config.get("n_freq_print")
n_freq_checkpoint = config.get("n_freq_checkpoint")
n_epochs = config.get("n_epochs")
# Train
checkpoint_prefix = join(utils.create_output_dir('out'),utils.get_stamp_from_log())
n_total_samples = 0.0
loss_vals = []
sample_count = []
for epoch in range(n_epochs):
# Resetting temporal loss used for logging
running_loss = 0.0
n_samples = 0
for batch_idx, minibatch in enumerate(dataloader):
for k, v in minibatch.items():
minibatch[k] = v.to(device)
gt_pose = minibatch.get('pose').to(dtype=torch.float32)
gt_scene = minibatch.get('scene').to(device)
minibatch['scene'] = None
batch_size = gt_pose.shape[0]
n_samples += batch_size
n_total_samples += batch_size
# Zero the gradients
optim.zero_grad()
with torch.no_grad():
res = apr(minibatch)
latent_x = res.get("latent_x")
latent_q = res.get("latent_q")
est_pose = res.get('pose')
scene_dist = res.get('scene_log_distr')
scene = torch.argmax(scene_dist, dim=1).to(dtype=torch.float32).unsqueeze(1)
est_latent_x, est_latent_q = pose_encoder(est_pose, scene)
with torch.no_grad():
res["global_desc_t"] = est_latent_x
res["global_desc_rot"] = est_latent_q
res_est = apr.forward_heads(res)
est_pose_from_encoding = res_est.get('pose')
criterion = mse_loss(latent_q, est_latent_q) + mse_loss(latent_x, est_latent_x) + pose_loss(est_pose_from_encoding, gt_pose)
# Collect for recoding and plotting
running_loss += criterion.item()
loss_vals.append(criterion.item())
sample_count.append(n_total_samples)
# Back prop
criterion.backward()
optim.step()
# Record loss and performance on train set
if batch_idx % n_freq_print == 0:
posit_err, orient_err = utils.pose_err(est_pose_from_encoding.detach(), gt_pose.detach())
logging.info("[Batch-{}/Epoch-{}] running camera pose loss: {:.3f}, "
"camera pose error: {:.2f}[m], {:.2f}[deg]".format(
batch_idx+1, epoch+1, (running_loss/n_samples),
posit_err.mean().item(),
orient_err.mean().item()))
# Save checkpoint
if (epoch % n_freq_checkpoint) == 0 and epoch > 0:
torch.save(pose_encoder.state_dict(), checkpoint_prefix + '_pose_encoder_checkpoint-{}.pth'.format(epoch))
# Scheduler update
scheduler.step()
logging.info('Training completed')
torch.save(pose_encoder.state_dict(), checkpoint_prefix + '_pose_encoder_final.pth'.format(epoch))
else: # Test
# Set to eval mode
apr.eval()
pose_encoder.eval()
# Set the dataset and data loader
transform = utils.test_transforms.get('baseline')
dataset = CameraPoseDataset(args.dataset_path, args.labels_file, transform)
loader_params = {'batch_size': 1,
'shuffle': False,
'num_workers': config.get('n_workers')}
dataloader = torch.utils.data.DataLoader(dataset, **loader_params)
stats = np.zeros((len(dataloader.dataset), 3))
with torch.no_grad():
for i, minibatch in enumerate(dataloader, 0):
for k, v in minibatch.items():
minibatch[k] = v.to(device)
gt_scene = minibatch.get('scene')
minibatch['scene'] = None # avoid using ground-truth scene during prediction
gt_pose = minibatch.get('pose').to(dtype=torch.float32)
# Forward pass to predict the pose
tic = time.time()
res = apr(minibatch)
est_pose = res.get('pose')
scene_dist = res.get('scene_log_distr')
scene = torch.argmax(scene_dist, dim=1).to(dtype=torch.float32).unsqueeze(1)
est_latent_x, est_latent_q = pose_encoder(est_pose, scene)
res["global_desc_t"] = est_latent_x
res["global_desc_rot"] = est_latent_q
res_est = apr.forward_heads(res)
est_pose_from_encoding = res_est.get('pose')
toc = time.time()
# Evaluate error
posit_err, orient_err = utils.pose_err(est_pose_from_encoding, gt_pose)
# Collect statistics
stats[i, 0] = posit_err.item()
stats[i, 1] = orient_err.item()
stats[i, 2] = (toc - tic)*1000
logging.info("Pose error: {:.3f}[m], {:.3f}[deg], inferred in {:.2f}[ms]".format(
stats[i, 0], stats[i, 1], stats[i, 2]))
# Record overall statistics
logging.info("Performance of {} on {}".format(args.checkpoint_path, args.labels_file))
logging.info("Median pose error: {:.3f}[m], {:.3f}[deg]".format(np.nanmedian(stats[:, 0]), np.nanmedian(stats[:, 1])))
logging.info("Mean inference time:{:.2f}[ms]".format(np.mean(stats[:, 2])))