Download scripts/train_cbf.py from codewithyug/certified-safe-neural-control: direct link, hf CLI and curl.
- Browser
- Download file 4.62 kB
-
https://huggingface.co/codewithyug/certified-safe-neural-control/resolve/main/scripts/train_cbf.py
- Command line
-
hf download hf://codewithyug/certified-safe-neural-control/scripts/train_cbf.py
-
curl -L -o train_cbf.py https://huggingface.co/codewithyug/certified-safe-neural-control/resolve/main/scripts/train_cbf.py
4.62 kB
| """ | |
| Phase 1: Neural CBF Training Script for 2D/3D Navigation | |
| Trains a compact MLP barrier h_theta(x) with CBFLoss over safe, unsafe, and boundary domains. | |
| """ | |
| import sys | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) | |
| import os | |
| import torch | |
| import torch.optim as optim | |
| import numpy as np | |
| from src.dynamics.toy_nav import DubinsCarSystem | |
| from src.cbf.network import NeuralCBF | |
| from src.cbf.loss import CBFLoss | |
| def generate_synthetic_data(num_samples: int = 5000): | |
| """ | |
| Generates state samples labeled as Safe, Unsafe, and Boundary relative to an obstacle. | |
| """ | |
| obstacle_pos = np.array([2.5, 0.0], dtype=np.float32) | |
| obstacle_radius = 1.0 | |
| # Domain: px in [0, 5], py in [-2.5, 2.5], theta in [-pi, pi], v in [0, 2] | |
| px = np.random.uniform(0.0, 5.0, size=(num_samples, 1)) | |
| py = np.random.uniform(-2.5, 2.5, size=(num_samples, 1)) | |
| theta = np.random.uniform(-np.pi, np.pi, size=(num_samples, 1)) | |
| v = np.random.uniform(0.0, 2.0, size=(num_samples, 1)) | |
| states = np.hstack([px, py, theta, v]).astype(np.float32) | |
| dist = np.linalg.norm(states[:, :2] - obstacle_pos, axis=1) | |
| safe_mask = dist > (obstacle_radius + 0.3) | |
| unsafe_mask = dist < (obstacle_radius - 0.1) | |
| boundary_mask = (dist >= (obstacle_radius - 0.2)) & (dist <= (obstacle_radius + 0.4)) | |
| x_safe = torch.tensor(states[safe_mask], dtype=torch.float32) | |
| x_unsafe = torch.tensor(states[unsafe_mask], dtype=torch.float32) | |
| x_boundary = torch.tensor(states[boundary_mask], dtype=torch.float32) | |
| return x_safe, x_unsafe, x_boundary, obstacle_pos, obstacle_radius | |
| def main(): | |
| print("=" * 60) | |
| print("PHASE 1: TRAINING COMPACT NEURAL CBF (Dubins System)") | |
| print("=" * 60) | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| print(f"[+] Training Device: {device}") | |
| sys_dyn = DubinsCarSystem(tau=0.5, K=1.0, dt=0.02) | |
| cbf_model = NeuralCBF(state_dim=4, hidden_dims=[64, 64], activation="tanh").to(device) | |
| loss_fn = CBFLoss( | |
| alpha_cbf=1.5, | |
| margin=0.1, | |
| weight_safe=1.0, | |
| weight_unsafe=2.0, | |
| weight_cbf=2.5, | |
| weight_reg=1e-4, | |
| ) | |
| optimizer = optim.Adam(cbf_model.parameters(), lr=1e-3) | |
| # Generate synthetic training sets | |
| x_safe, x_unsafe, x_boundary, obs_pos, obs_r = generate_synthetic_data(num_samples=8000) | |
| print(f"[+] Dataset: {len(x_safe)} Safe | {len(x_unsafe)} Unsafe | {len(x_boundary)} Boundary samples") | |
| # Move to device | |
| x_safe = x_safe.to(device) | |
| x_unsafe = x_unsafe.to(device) | |
| x_boundary = x_boundary.to(device) | |
| # Compute drift f and actuation g on boundary points | |
| batch_b = len(x_boundary) | |
| f_b_list = [sys_dyn.f(x_boundary[i].detach().cpu().numpy()) for i in range(batch_b)] | |
| g_b_list = [sys_dyn.g(x_boundary[i].detach().cpu().numpy()) for i in range(batch_b)] | |
| f_boundary = torch.tensor(np.array(f_b_list), dtype=torch.float32, device=device) | |
| g_boundary = torch.tensor(np.array(g_b_list), dtype=torch.float32, device=device) | |
| u_nominal = torch.zeros((batch_b, 2), dtype=torch.float32, device=device) | |
| # Training loop | |
| epochs = 60 | |
| batch_size = 256 | |
| print("\n[*] Starting Neural CBF Training Loop...") | |
| for epoch in range(1, epochs + 1): | |
| cbf_model.train() | |
| optimizer.zero_grad() | |
| # Subsample batches | |
| idx_s = torch.randperm(len(x_safe))[:batch_size] | |
| idx_u = torch.randperm(len(x_unsafe))[:batch_size] | |
| idx_b = torch.randperm(len(x_boundary))[:batch_size] | |
| loss_dict = loss_fn( | |
| model=cbf_model, | |
| x_safe=x_safe[idx_s], | |
| x_unsafe=x_unsafe[idx_u], | |
| x_boundary=x_boundary[idx_b], | |
| f_boundary=f_boundary[idx_b], | |
| g_boundary=g_boundary[idx_b], | |
| u_nominal=u_nominal[idx_b], | |
| ) | |
| total_loss = loss_dict["total_loss"] | |
| total_loss.backward() | |
| optimizer.step() | |
| if epoch % 10 == 0 or epoch == epochs: | |
| print( | |
| f"Epoch [{epoch:02d}/{epochs}] | " | |
| f"Total: {total_loss.item():.4f} | " | |
| f"Safe: {loss_dict['loss_safe'].item():.4f} | " | |
| f"Unsafe: {loss_dict['loss_unsafe'].item():.4f} | " | |
| f"CBF Ineq: {loss_dict['loss_cbf'].item():.4f}" | |
| ) | |
| # Save checkpoint | |
| os.makedirs("checkpoints", exist_ok=True) | |
| checkpoint_path = "checkpoints/cbf_dubins.pt" | |
| torch.save(cbf_model.state_dict(), checkpoint_path) | |
| print(f"\n[+] Checkpoint saved successfully: {checkpoint_path}") | |
| if __name__ == "__main__": | |
| main() | |