File size: 4,618 Bytes
0210a65 | 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 | """
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()
|