Repository navigation
Expand file tree
/
Copy pathinference_mpinets.py
More file actions
executable file
·263 lines (237 loc) · 12.5 KB
/
Copy pathinference_mpinets.py
File metadata and controls
executable file
·263 lines (237 loc) · 12.5 KB
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import copy
import os
import time
import hydra
import torch
import random
import numpy as np
import torch.nn as nn
import kaolin as kl
from typing import Dict
from argparse import Namespace
from omegaconf import DictConfig, OmegaConf
from env.agent.mec_kinova import MecKinova
from env.base import create_enviroment
from env.sampler.mk_sampler import MecKinovaSampler
from models.planner.mk_motion_policy_planning import compute_grasp_energy
from third_party.grasp_diffusion.se3dif.models.loader import load_model
from utils.meckinova_utils import transform_configuration_torch
from utils.misc import compute_model_dim
from datamodule.base import create_datamodule
from models.base import create_model
from utils.transform import transform_pointcloud_torch
OmegaConf.register_new_resolver("eval", eval, replace=True)
def rollout_mpinets(
mdl: nn.Module,
data: Dict[str, torch.Tensor],
mk_sampler: MecKinovaSampler,
num_pc_item: Dict[str, int],
max_rollout_length: int=60,
) -> np.ndarray:
""" Rolls out the policy using the provided model and data for a specified maximum number of steps,
updating the robot configuration and point cloud at each step. Depending on the task type ('pick',
'place', or 'goal-reach'), it computes the trajectory and searches for the step with the minimum
energy (grasping, placement, or goal-reaching energy).
Args:
mdl [nn.Module]: The motion generation network (policy) to be used for predicting the next configuration.
data [Dict[str, torch.Tensor]]: Input data containing point clouds, transformation matrices, configurations,
and other task-specific information.
mk_sampler [MecKinovaSampler]: A sampler for generating points on the robot's surface and computing end-effector poses.
num_pc_item [Dict[str, int]]: Dictionary specifying the number of agent, scene, object, placement area, and target
points in the point cloud.
max_rollout_length [int, optional]: The maximum number of rollout steps to perform. Default is 60.
Return:
np.ndarray: The trajectory of robot configurations over the rollout, with shape [B, L, D], where B is batch size, L is rollout
length, and D is configuration dimension.
np.ndarray: The indices of the steps with the minimum energy (grasping, placement, or goal-reaching), depending on the task type.
"""
B, L = data['xyz'].shape[0], max_rollout_length
device = data['xyz'].device
task_type = data['task_name'][0]
point_cloud = data['xyz']
# number of points
a_num = num_pc_item['num_agent_points']
s_num = num_pc_item['num_scene_points']
o_num = num_pc_item['num_object_points']
p_num = num_pc_item['num_placement_area_points']
t_num = num_pc_item['num_target_points']
# transformation matrices
T_aw = copy.deepcopy(data['T_aw']) # [B, 4, 4]
if task_type == 'pick':
T_ow = copy.deepcopy(data['T_ow']) # [B, 4, 4]
T_wo = torch.inverse(T_ow) # [B, 4, 4]
T_oa = copy.deepcopy(data['T_oa']) # [B, 4, 4]
T_ao = torch.inverse(T_oa) # [B, 4, 4]
elif task_type == 'place':
T_ow_final = copy.deepcopy(data['T_ow_final'])
T_wo_final = torch.inverse(T_ow_final)
T_oa_init = copy.deepcopy(data['T_oa_init'])
T_ao_init = torch.inverse(T_oa_init)
T_eeo = copy.deepcopy(data['grasping_pose'])
# load object point cloud
if task_type == 'pick':
object_pcs_a = copy.deepcopy(data['object_pc_a']) # [B, N2, 3]
elif task_type == 'place':
# initial object point cloud in agent frame
object_pcs_a = copy.deepcopy(data['object_pc_a']) # [B, N2, 3]
# object point cloud in self frame
object_pcs_o = transform_pointcloud_torch(object_pcs_a, T_ao_init)
object_placement_pcs_o = copy.deepcopy(data['object_placement_pc_o'])
scene_placement_pcs_a = copy.deepcopy(data['scene_placement_pc_a'])
else:
target_pcs_a = copy.deepcopy((data['target_pc_a']))
# transformation in data normalization
trans_mats = data['trans_mat']
trans_mats_inv = torch.inverse(trans_mats)
rot_angles = data['rot_angle']
rot_angles_inv = -rot_angles
# unnormalize and transform initial q
q_norm = data['configuration'] # normalized configuration in local scene center frame
q_unnorm = MecKinova.unnormalize_joints(q_norm) # unnormalized configuration in local scene center frame
q_unnorm = transform_configuration_torch(q_unnorm, trans_mats_inv, rot_angles_inv) # unnormalized configuration in agent initial frame
trajs = [q_unnorm] # store complete trajectory
for h in range(max_rollout_length - 1):
# predict next configuration
q_hat_norm = mdl(point_cloud, q_norm)
# q_hat_norm = torch.clamp(q_hat_norm, min=-1, max=1)
q_hat_unnorm = MecKinova.unnormalize_joints(q_hat_norm) # in local scene center frame
q_hat_unnorm = transform_configuration_torch(q_hat_unnorm, trans_mats_inv, rot_angles_inv) # in agent initial frame
trajs.append(q_hat_unnorm)
# update q_norm
q_norm = q_hat_norm
# update point_cloud
agent_pcs_a = mk_sampler.sample(q_hat_unnorm).type_as(point_cloud)
agent_pcs_s = transform_pointcloud_torch(agent_pcs_a, trans_mats)
point_cloud[:, :a_num, :3] = agent_pcs_s
if task_type == 'place':
T_eea = mk_sampler.end_effector_pose(q_hat_unnorm) # [B, 4, 4]
T_oa = torch.matmul(T_eea, torch.inverse(T_eeo)) # [B, 4, 4]
object_pcs_a = transform_pointcloud_torch(copy.deepcopy(object_pcs_o), T_oa)
object_pcs_s = transform_pointcloud_torch(object_pcs_a, trans_mats)
point_cloud[:, a_num + s_num:-p_num, :3] = object_pcs_s
trajs = np.asarray([t.detach().cpu().numpy() for t in trajs])
trajs = torch.as_tensor(trajs).to(device=device) # [L, B, D]
trajs = trajs.transpose(0, 1) # [B, L, D]
## for 'pick' task, we search locations with the least grasping energy in each trajectory
if task_type == 'pick':
# load grasp-energy model
args = Namespace(device=device, model='grasp_dif_multi', batch=L)
model_args = {'device': device, 'pretrained_model': args.model}
grasp_energy_model = load_model(model_args)
object_pcs_o = transform_pointcloud_torch(object_pcs_a, T_ao)
# normalize object point clouds
object_pcs_o *= 8.
object_pcs_o_mean = torch.mean(object_pcs_o, dim=1).unsqueeze(1)
object_pcs_o -= object_pcs_o_mean # [B, N, 3]
# calculate the grasping energy for each trajectory
min_grasp_enery_index = torch.tensor([]).to(device=device)
for b in range(B):
object_pc_o = object_pcs_o[b,...]
context = object_pc_o[None,...]
grasp_energy_model.set_latent(context, batch=args.batch)
H_a = mk_sampler.end_effector_pose(trajs[b,...])
H_w = torch.matmul(T_aw[b,...], H_a)
H_o = torch.matmul(T_wo[b,...], H_w)
# normalize SE(3) transformation matrix
H_o[..., :3, -1] *= 8
H_o[..., :3, -1] = H_o[..., :3, -1] - object_pcs_o_mean[b,...]
# grasp energy
grasp_energy, _ = compute_grasp_energy(grasp_energy_model, H_o)
_, min_index = torch.min(grasp_energy, dim=0)
min_index = torch.as_tensor([max_rollout_length], device=device)
min_grasp_enery_index = torch.cat((min_grasp_enery_index, min_index), dim=0)
return trajs.detach().cpu().numpy(), min_grasp_enery_index.detach().cpu().numpy().astype(np.int16)
## for 'place' task, we search locations with the least placement energy in each trajectory
elif task_type == 'place':
# calculate the grasping energy for each trajectory
min_place_enery_index = torch.tensor([]).to(device=device)
for b in range(B):
T_eea = mk_sampler.end_effector_pose(trajs[b,...]) # [L, 4, 4]
T_oa = torch.matmul(T_eea, torch.inverse(T_eeo[b,...]).repeat(L, 1, 1))
object_placement_pc_a = transform_pointcloud_torch(
object_placement_pcs_o[b,...].repeat(L, 1, 1), torch.inverse(T_oa)
)
scene_placement_pc_a = scene_placement_pcs_a[b,...].repeat(L, 1, 1)
place_energy, _ = kl.metrics.pointcloud.sided_distance(
object_placement_pc_a, scene_placement_pc_a
)
_, min_index = torch.min(place_energy, dim=0)
min_index = torch.as_tensor([max_rollout_length], device=device)
min_place_enery_index = torch.cat((min_place_enery_index, min_index), dim=0)
return trajs.detach().cpu().numpy(), min_place_enery_index.detach().cpu().numpy().astype(np.int16)
## for 'goal-reach' task, we search locations with the least goal-reaching energy in each trajectory
else:
# calculate the grasping energy for each trajectory
min_goal_reach_enery_index = torch.tensor([]).to(device=device)
for b in range(B):
eef_pc_a = mk_sampler.sample_end_effector(trajs[b,...], t_num, True) # [L, N, 3]
target_pc_a = target_pcs_a[b,...].repeat(L, 1, 1) # [L, N, 3]
# goal_reach_energy = point_clouds_match_loss(eef_pc_a, target_pc_a, 'none').sum(dim=-1).sum(dim=-1).unsqueeze(1) # [L, 1]
# min_index = torch.as_tensor([max_rollout_length], device=device)
goal_reach_energy = kl.metrics.pointcloud.chamfer_distance(eef_pc_a, target_pc_a).unsqueeze(1)
_, min_index = torch.min(goal_reach_energy, dim=0)
min_goal_reach_enery_index = torch.cat((min_goal_reach_enery_index, min_index), dim=0)
return trajs.detach().cpu().numpy(), min_goal_reach_enery_index.detach().cpu().numpy().astype(np.int16)
@hydra.main(version_base=None, config_path="./configs", config_name="default")
def run_inference(config: DictConfig) -> None:
## compute modeling dimension according to task
config.model.d_x = compute_model_dim(config.task)
if os.environ.get('SLURM') is not None:
config.slurm = True # update slurm config
device = f'cuda:0' if config.gpus is not None else 'cpu'
## prepare test dataset for evaluating on planning task
dm = create_datamodule(cfg=config.task.datamodule, slurm=config.slurm)
dl = dm.get_test_dataloader()
## create model and diffuser, load ckpt, create and load optimizer and planner for diffuser
ckpt_path = os.path.join(config.exp_dir, "last.ckpt")
mdl = create_model(config, ckpt_path=ckpt_path, slurm=config.slurm, **{"device": device})
mdl.to(device=device)
## create meckinova motion policy test environment
env = create_enviroment(config.task.environment)
## number of point cloud
num_pc_item = {
"num_scene_points": config.task.datamodule.num_scene_points,
"num_agent_points": config.task.datamodule.num_agent_points,
"num_object_points": config.task.datamodule.num_object_points,
"num_placement_area_points": config.task.datamodule.num_placement_area_points,
"num_target_points": config.task.datamodule.num_target_points
}
## inference
with torch.no_grad():
mdl.eval()
for i, data in enumerate(dl):
for key in data:
if torch.is_tensor(data[key]):
data[key] = data[key].to(device)
start_time = time.time()
## create meckinova sampler
mk_sampler = MecKinovaSampler(
device=device,
num_fixed_points=num_pc_item['num_agent_points'],
use_cache=True,
)
## rolls out the policy until the success criteria are met.
trajs_unorm_a, termination_index = rollout_mpinets(mdl, data, mk_sampler, num_pc_item)
## evaluation mode supports only 1 batch_size
traj_unorm_a = trajs_unorm_a[-1][:termination_index[-1] + 1]
## evaluate trajectory
env.evaluate(
id=i,
dt=0.08, # we assume the time step for the trajectory is 0.08
time=time.time() - start_time,
data=data, traj=traj_unorm_a, agent_object=MecKinova
)
env.visualize(data, traj_unorm_a)
print("Overall Metrics")
env.print_overall_metrics()
if __name__ == '__main__':
## set random seed
seed = 0
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
run_inference()