Hang917 commited on
Commit
c09b668
·
1 Parent(s): c1dea15

FIX: gpu ram and control frequency

Browse files
Files changed (2) hide show
  1. mppi/task/bb1d_track.py +105 -30
  2. plot/plot_mppi.py +124 -0
mppi/task/bb1d_track.py CHANGED
@@ -122,7 +122,6 @@ class NeuralHybridDynamics:
122
  module.load_state_dict(filtered_state, strict=False)
123
 
124
  if self.model_type == 'hybrid':
125
-
126
  # Load each component (guarded)
127
  if hasattr(self.model, 'encoder') and (self.model.encoder is not None) and ('encoder' in self.checkpoint):
128
  safe_load_state_dict(self.model.encoder, self.checkpoint['encoder'], 'encoder')
@@ -174,13 +173,14 @@ class NeuralHybridDynamics:
174
  at_batch[:, 0, 0:-1] = action[:, 0, :] # use only the first frame to init the encoder
175
 
176
  # Inference on the model's internal eval grid, then decode to x_trajectory
177
- out = self.model.inference(xt_batch.to(torch.float32), at_batch.to(torch.float32), infer_x=True)
 
178
 
179
- t_eval = out.get('t_eval', t_batch) # [B, Te] or [Te]
180
- x_traj = out['x_trajectory'] # [B, Te, Dx]
181
- if self.model_type == 'hybrid':
182
- z_traj_raw = out['z_trajectory'] # [Te, B, latent_dim] -> [20, 512, 4]
183
- self.z_traj = z_traj_raw.permute(1, 0, 2) # Convert to [B, Te, latent_dim] -> [512, 20, 4]
184
 
185
  # Interpolate from t_eval to our target sampling times
186
  x_pred = interpolate_trajectory(t_eval, t_batch - t_batch[:, :1], x_traj) # [B, H, Dx]
@@ -217,7 +217,8 @@ class NeuralHybridDynamics:
217
  class BBTrack:
218
  def __init__(self):
219
  self.parser = self.parse_bb_track_args()
220
- self.control_dt = 1/100 # 50Hz
 
221
  self.horizon = 20
222
  self.iterations = 10
223
  self.state_dims = 4
@@ -262,7 +263,7 @@ class BBTrack:
262
  def parse_bb_track_args(self):
263
  """Parse command line arguments for data collection"""
264
  parser = argparse.ArgumentParser(description="Collect bouncing ball dataset")
265
- parser.add_argument("--steps", type=int, default=16000, help="Steps to run")
266
  parser.add_argument("--realtime", action="store_true", help="Match simulation speed to real time")
267
  parser.add_argument("--seed", type=int, default=42, help="Random seed")
268
  parser.add_argument("--headless", action="store_true", help="Run in headless mode (no rendering)")
@@ -468,13 +469,70 @@ class BBTrack:
468
  print("Warning: Target sphere is not a mocap body")
469
 
470
  def vis_tar_traj(self, env):
471
- target_z = torch.abs(torch.sin(self.omega * torch.tensor(self.current_simulation_time,device=self.device))) * self.amplitude + self.offset
472
- target_x = torch.ones_like(target_z) * 0
473
- target_y = torch.ones_like(target_z) * 0
474
- target_pos = torch.stack([target_x, target_y, target_z], dim=-1)
 
475
  # visualize target trajectory
476
  return target_pos
477
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478
 
479
 
480
 
@@ -493,23 +551,32 @@ class BBTrack:
493
  # Update target visualization
494
  self.update_target_visualization()
495
 
496
- if step % (1/self.control_dt) == 0:
497
- # Convert obs to torch tensor if needed
498
- if isinstance(obs, np.ndarray):
499
- obs_tensor = torch.from_numpy(obs).float().to(self.device).unsqueeze(0) # Add batch dim
500
- else:
501
- obs_tensor = obs
502
-
503
- # print("Ball GT:zt:",obs_tensor[0,0])
504
- # print("Board GT:zt:",obs_tensor[0,2]) # TODO
505
- target_z = torch.abs(torch.sin(self.omega * torch.tensor(self.current_simulation_time,device=self.device))) * self.amplitude + self.offset # [horizon]
506
- # print("Ball Tar:zt::",target_z)
507
-
508
- # Call the MPPI controller
509
- action_tensor = self.controller._plan(obs_tensor, obs_tensor, t0=(step==0))
510
- action = action_tensor.cpu().numpy().flatten() # Convert back to numpy
511
- # action = action.reshape(1, -1)
512
- # print(action.shape)
 
 
 
 
 
 
 
 
 
513
 
514
 
515
 
@@ -525,6 +592,14 @@ class BBTrack:
525
 
526
  print("Demo simulation completed")
527
 
 
 
 
 
 
 
 
 
528
 
529
  if __name__ == "__main__":
530
  bb_track = BBTrack()
 
122
  module.load_state_dict(filtered_state, strict=False)
123
 
124
  if self.model_type == 'hybrid':
 
125
  # Load each component (guarded)
126
  if hasattr(self.model, 'encoder') and (self.model.encoder is not None) and ('encoder' in self.checkpoint):
127
  safe_load_state_dict(self.model.encoder, self.checkpoint['encoder'], 'encoder')
 
173
  at_batch[:, 0, 0:-1] = action[:, 0, :] # use only the first frame to init the encoder
174
 
175
  # Inference on the model's internal eval grid, then decode to x_trajectory
176
+ with torch.no_grad():
177
+ out = self.model.inference(xt_batch.to(torch.float32), at_batch.to(torch.float32), infer_x=True)
178
 
179
+ t_eval = out.get('t_eval', t_batch) # [B, Te] or [Te]
180
+ x_traj = out['x_trajectory'] # [B, Te, Dx]
181
+ if self.model_type == 'hybrid':
182
+ z_traj_raw = out['z_trajectory'] # [Te, B, latent_dim] -> [20, 512, 4]
183
+ self.z_traj = z_traj_raw.permute(1, 0, 2) # Convert to [B, Te, latent_dim] -> [512, 20, 4]
184
 
185
  # Interpolate from t_eval to our target sampling times
186
  x_pred = interpolate_trajectory(t_eval, t_batch - t_batch[:, :1], x_traj) # [B, H, Dx]
 
217
  class BBTrack:
218
  def __init__(self):
219
  self.parser = self.parse_bb_track_args()
220
+ self.control_dt = 1/100 # 100Hz
221
+ self.control_hz = 100
222
  self.horizon = 20
223
  self.iterations = 10
224
  self.state_dims = 4
 
263
  def parse_bb_track_args(self):
264
  """Parse command line arguments for data collection"""
265
  parser = argparse.ArgumentParser(description="Collect bouncing ball dataset")
266
+ parser.add_argument("--steps", type=int, default=10000, help="Steps to run")
267
  parser.add_argument("--realtime", action="store_true", help="Match simulation speed to real time")
268
  parser.add_argument("--seed", type=int, default=42, help="Random seed")
269
  parser.add_argument("--headless", action="store_true", help="Run in headless mode (no rendering)")
 
469
  print("Warning: Target sphere is not a mocap body")
470
 
471
  def vis_tar_traj(self, env):
472
+ with torch.no_grad():
473
+ target_z = torch.abs(torch.sin(self.omega * torch.tensor(self.current_simulation_time,device=self.device))) * self.amplitude + self.offset
474
+ target_x = torch.zeros_like(target_z)
475
+ target_y = torch.zeros_like(target_z)
476
+ target_pos = torch.stack([target_x, target_y, target_z], dim=-1)
477
  # visualize target trajectory
478
  return target_pos
479
 
480
+ def log_step(self, state, target_pos, cost, action=None):
481
+ """Log data to arrays at each step"""
482
+ # Initialize arrays
483
+ if not hasattr(self, 'log_states'):
484
+ self.log_states = []
485
+ self.log_targets = []
486
+ self.log_costs = []
487
+ self.log_times = []
488
+ self.log_actions = []
489
+
490
+ # Convert tensors to numpy and add to arrays
491
+ if isinstance(state, torch.Tensor):
492
+ state = state.cpu().numpy()
493
+ if isinstance(target_pos, torch.Tensor):
494
+ target_pos = target_pos.cpu().numpy()
495
+ if isinstance(cost, torch.Tensor):
496
+ cost = cost.detach().cpu().numpy()
497
+
498
+ self.log_states.append(state)
499
+ self.log_targets.append(target_pos)
500
+ self.log_costs.append(cost)
501
+ self.log_times.append(self.current_simulation_time)
502
+ if action is not None:
503
+ if isinstance(action, torch.Tensor):
504
+ action = action.cpu().numpy()
505
+ self.log_actions.append(action)
506
+ else:
507
+ self.log_actions.append(0.0)
508
+
509
+ def save_log(self):
510
+ """Save all data to files"""
511
+ if not hasattr(self, 'log_states') or len(self.log_states) == 0:
512
+ return
513
+
514
+ from datetime import datetime
515
+ import shutil
516
+
517
+ # Create directory
518
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
519
+ log_dir = f"/home/lau/sim/DynaTraj/logs/bb/{timestamp}"
520
+ os.makedirs(log_dir, exist_ok=True)
521
+
522
+ # Save data
523
+ np.savez_compressed(
524
+ f"{log_dir}/{timestamp}.npz",
525
+ states=np.array(self.log_states),
526
+ targets=np.array(self.log_targets),
527
+ costs=np.array(self.log_costs),
528
+ times=np.array(self.log_times),
529
+ actions=np.array(self.log_actions)
530
+ )
531
+
532
+ # Copy code file
533
+ shutil.copy2("/home/lau/sim/DynaTraj/mppi/task/bb1d_track.py", f"{log_dir}/bb1d_track.py")
534
+
535
+ print(f"Saved {len(self.log_states)} data points to {log_dir}")
536
 
537
 
538
 
 
551
  # Update target visualization
552
  self.update_target_visualization()
553
 
554
+ if step % (1000/self.control_hz) == 0:
555
+ print(self.current_simulation_time)
556
+
557
+ with torch.no_grad(): # Prevent gradient accumulation
558
+ # Convert obs to torch tensor if needed
559
+ if isinstance(obs, np.ndarray):
560
+ obs_tensor = torch.from_numpy(obs).float().to(self.device).unsqueeze(0) # Add batch dim
561
+ else:
562
+ obs_tensor = obs
563
+
564
+ # Call the MPPI controller
565
+ action_tensor = self.controller._plan(obs_tensor, obs_tensor, t0=(step==0))
566
+ action = action_tensor.cpu().numpy().flatten() # Convert back to numpy
567
+
568
+ # Log data: state, target, and cost
569
+ target_pos = self.vis_tar_traj(self.env)
570
+ # Compute cost for current state
571
+ dummy_action = torch.zeros(1, self.horizon, 1, device=self.device)
572
+ current_cost = self.cost_function(obs_tensor.unsqueeze(1).expand(-1, self.horizon, -1), dummy_action)
573
+
574
+ # Log data
575
+ self.log_step(obs_tensor, target_pos, current_cost.mean(), action)
576
+
577
+ # Clear cache periodically
578
+ if step % 1000 == 0:
579
+ torch.cuda.empty_cache()
580
 
581
 
582
 
 
592
 
593
  print("Demo simulation completed")
594
 
595
+ # Save log data
596
+ self.save_log()
597
+
598
+ # Clean up GPU memory
599
+ torch.cuda.empty_cache()
600
+ if hasattr(self, 'z_traj'):
601
+ del self.z_traj
602
+
603
 
604
  if __name__ == "__main__":
605
  bb_track = BBTrack()
plot/plot_mppi.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import matplotlib.pyplot as plt
3
+ import argparse
4
+ import os
5
+ import glob
6
+
7
+ def load_data(log_path):
8
+ """Load data from npz file"""
9
+ data = np.load(log_path)
10
+ return {
11
+ 'states': data['states'],
12
+ 'targets': data['targets'],
13
+ 'costs': data['costs'],
14
+ 'times': data['times'],
15
+ 'actions': data['actions']
16
+ }
17
+
18
+ def plot_ball_trajectory(times, states, save_path):
19
+ """Plot ball z-axis trajectory"""
20
+ ball_z = states[:, 0, 0] if states.ndim == 3 else states[:, 0]
21
+
22
+ plt.figure(figsize=(10, 6))
23
+ plt.plot(times, ball_z, 'b-', linewidth=2, label='Ball Z Position')
24
+ plt.xlabel('Time (s)')
25
+ plt.ylabel('Z Position (m)')
26
+ plt.title('Ball Trajectory')
27
+ plt.grid(True, alpha=0.3)
28
+ plt.legend()
29
+ plt.tight_layout()
30
+ plt.savefig(f"{save_path}/ball_trajectory.png", dpi=300)
31
+ plt.close()
32
+
33
+ def plot_reference_trajectory(times, targets, save_path):
34
+ """Plot reference z-axis trajectory"""
35
+ ref_z = targets[:, 2] if targets.ndim == 2 else targets[:, 0, 2]
36
+
37
+ plt.figure(figsize=(10, 6))
38
+ plt.plot(times, ref_z, 'r--', linewidth=2, label='Reference Z Position')
39
+ plt.xlabel('Time (s)')
40
+ plt.ylabel('Z Position (m)')
41
+ plt.title('Reference Trajectory')
42
+ plt.grid(True, alpha=0.3)
43
+ plt.legend()
44
+ plt.tight_layout()
45
+ plt.savefig(f"{save_path}/reference_trajectory.png", dpi=300)
46
+ plt.close()
47
+
48
+ def plot_cost(times, costs, save_path):
49
+ """Plot cost over time"""
50
+ plt.figure(figsize=(10, 6))
51
+ plt.plot(times, costs, 'g-', linewidth=2, label='Cost')
52
+ plt.xlabel('Time (s)')
53
+ plt.ylabel('Cost')
54
+ plt.title('Cost Over Time')
55
+ plt.grid(True, alpha=0.3)
56
+ plt.legend()
57
+ plt.tight_layout()
58
+ plt.savefig(f"{save_path}/cost.png", dpi=300)
59
+ plt.close()
60
+
61
+ def plot_actions(times, actions, save_path):
62
+ """Plot actions over time"""
63
+ plt.figure(figsize=(10, 6))
64
+ plt.plot(times, actions, 'm-', linewidth=2, label='Action')
65
+ plt.xlabel('Time (s)')
66
+ plt.ylabel('Action Value')
67
+ plt.title('Actions Over Time')
68
+ plt.grid(True, alpha=0.3)
69
+ plt.legend()
70
+ plt.tight_layout()
71
+ plt.savefig(f"{save_path}/actions.png", dpi=300)
72
+ plt.close()
73
+
74
+ def plot_comparison(times, states, targets, save_path):
75
+ """Plot ball and reference trajectories together"""
76
+ ball_z = states[:, 0, 0] if states.ndim == 3 else states[:, 0]
77
+ ref_z = targets[:, 2] if targets.ndim == 2 else targets[:, 0, 2]
78
+
79
+ plt.figure(figsize=(12, 6))
80
+ plt.plot(times, ball_z, 'b-', linewidth=2, label='Ball Z Position')
81
+ plt.plot(times, ref_z, 'r--', linewidth=2, label='Reference Z Position')
82
+ plt.xlabel('Time (s)')
83
+ plt.ylabel('Z Position (m)')
84
+ plt.title('Ball vs Reference Trajectory')
85
+ plt.grid(True, alpha=0.3)
86
+ plt.legend()
87
+ plt.tight_layout()
88
+ plt.savefig(f"{save_path}/comparison.png", dpi=300)
89
+ plt.close()
90
+
91
+ def main():
92
+ parser = argparse.ArgumentParser(description='Plot MPPI tracking results')
93
+ parser.add_argument('--log_dir',default='/home/lau/sim/DynaTraj/logs/bb/20250924_104647', type=str, help='Path to log directory')
94
+ args = parser.parse_args()
95
+
96
+ # Find npz file
97
+ npz_files = glob.glob(os.path.join(args.log_dir, "*.npz"))
98
+ if not npz_files:
99
+ print(f"No npz files found in {args.log_dir}")
100
+ return
101
+
102
+ npz_file = npz_files[0]
103
+ print(f"Loading data from {npz_file}")
104
+
105
+ # Load data
106
+ data = load_data(npz_file)
107
+ times = data['times']
108
+ states = data['states']
109
+ targets = data['targets']
110
+ costs = data['costs']
111
+ actions = data['actions']
112
+
113
+ # Create plots
114
+ print("Generating plots...")
115
+ plot_ball_trajectory(times, states, args.log_dir)
116
+ plot_reference_trajectory(times, targets, args.log_dir)
117
+ plot_cost(times, costs, args.log_dir)
118
+ plot_actions(times, actions, args.log_dir)
119
+ plot_comparison(times, states, targets, args.log_dir)
120
+
121
+ print(f"Plots saved to {args.log_dir}")
122
+
123
+ if __name__ == "__main__":
124
+ main()