Download src/pipeline.py from codewithyug/certified-safe-neural-control: direct link, hf CLI and curl.
- Browser
- Download file 6.65 kB
-
https://huggingface.co/codewithyug/certified-safe-neural-control/resolve/main/src/pipeline.py
- Command line
-
hf download hf://codewithyug/certified-safe-neural-control/src/pipeline.py
-
curl -L -o pipeline.py https://huggingface.co/codewithyug/certified-safe-neural-control/resolve/main/src/pipeline.py
6.65 kB
| """ | |
| Certified Safety Pipeline | |
| Unified high-level interface for loading pretrained Neural CBFs, evaluating Lie derivatives, | |
| filtering unsafe actions via convex QP, and updating online conformal margins under distribution shift. | |
| """ | |
| from typing import Tuple, Dict, Any, Optional, Union | |
| import os | |
| import time | |
| import numpy as np | |
| import torch | |
| from pathlib import Path | |
| from src.cbf.network import NeuralCBF | |
| from src.filter.cbf_qp import CBFQPSafetyFilter | |
| from src.calibration.adapt_nc import AdaptNCCalibrator | |
| from src.dynamics.toy_nav import DubinsCarSystem | |
| class CertifiedSafetyPipeline: | |
| """ | |
| Production-ready high-level pipeline for Certified-Safe Neural Control. | |
| Integrates: | |
| 1. Pretrained Neural CBF h_theta(x) | |
| 2. Lie Derivative Evaluation: L_f h, L_g h | |
| 3. Real-Time Convex Quadratic Program (OSQP Filter) | |
| 4. Online Conformal Non-Exchangeable Calibrator (AdaptNC) | |
| """ | |
| def __init__( | |
| self, | |
| cbf_net: NeuralCBF, | |
| system: Any, | |
| alpha_cbf: float = 1.5, | |
| alpha_risk: float = 0.01, | |
| eta: float = 0.05, | |
| slack_penalty: float = 1e4, | |
| device: str = "cpu", | |
| ): | |
| self.device = torch.device(device) | |
| self.cbf_net = cbf_net.to(self.device) | |
| self.cbf_net.eval() | |
| self.system = system | |
| self.alpha_cbf = alpha_cbf | |
| # Initialize OSQP convex safety filter | |
| self.qp_filter = CBFQPSafetyFilter( | |
| control_dim=self.system.control_dim, | |
| u_min=self.system.u_min, | |
| u_max=self.system.u_max, | |
| alpha_cbf=alpha_cbf, | |
| slack_penalty=slack_penalty, | |
| ) | |
| # Initialize online adaptive conformal calibrator | |
| self.calibrator = AdaptNCCalibrator( | |
| alpha_risk=alpha_risk, | |
| eta=eta, | |
| c_max=4.0, | |
| ) | |
| self._last_state = None | |
| self._last_h = None | |
| self._last_u = None | |
| self._last_Lf = None | |
| self._last_Lg = None | |
| def from_pretrained( | |
| cls, | |
| checkpoint_path: Union[str, Path] = "checkpoints/cbf_dubins.pt", | |
| system_type: str = "dubins", | |
| device: str = "cpu", | |
| **kwargs, | |
| ) -> "CertifiedSafetyPipeline": | |
| """ | |
| Loads a pretrained Neural CBF from disk and instantiates the certified safety pipeline. | |
| """ | |
| ckpt = Path(checkpoint_path) | |
| if not ckpt.exists(): | |
| raise FileNotFoundError(f"Checkpoint not found at: {ckpt}") | |
| state_dict = torch.load(ckpt, map_location=device, weights_only=True) | |
| if system_type.lower() == "dubins": | |
| state_dim = 4 | |
| # Determine hidden dimensions from state_dict | |
| if "net.4.weight" in state_dict and "net.6.weight" in state_dict: | |
| hidden_dims = [128, 128, 64] | |
| else: | |
| hidden_dims = [64, 64] | |
| system = DubinsCarSystem(tau=0.5, K=1.0, dt=0.02) | |
| elif system_type.lower() == "quadrotor": | |
| state_dim = 12 | |
| hidden_dims = [64, 64] | |
| from src.dynamics.quadrotor_6dof import Quadrotor6DoFSystem | |
| system = Quadrotor6DoFSystem(dt=0.01) | |
| else: | |
| raise ValueError(f"Unsupported system_type: {system_type}. Choose 'dubins' or 'quadrotor'.") | |
| cbf_net = NeuralCBF(state_dim=state_dim, hidden_dims=hidden_dims, activation="tanh") | |
| cbf_net.load_state_dict(state_dict) | |
| return cls(cbf_net=cbf_net, system=system, device=device, **kwargs) | |
| def filter_action( | |
| self, | |
| state: np.ndarray, | |
| u_nominal: np.ndarray, | |
| dt: float = 0.02, | |
| actual_next_state: Optional[np.ndarray] = None, | |
| ) -> Tuple[np.ndarray, Dict[str, Any]]: | |
| """ | |
| Filters nominal control input u_nominal to guarantee certified forward invariance. | |
| Args: | |
| state: Current state vector in R^n | |
| u_nominal: Unfiltered nominal control action in R^m | |
| dt: Integration time step | |
| actual_next_state: Optional realized state from previous step to update conformal margin. | |
| Returns: | |
| u_safe: Certified safe control action in R^m | |
| info: Telemetry dictionary with barrier value, gamma margin, solve time, etc. | |
| """ | |
| x_np = np.asarray(state, dtype=np.float32) | |
| u_nom_np = np.asarray(u_nominal, dtype=np.float32) | |
| # 1. Update online conformal margin if feedback state provided | |
| if actual_next_state is not None and self._last_state is not None: | |
| with torch.no_grad(): | |
| x_next_t = torch.tensor(actual_next_state, dtype=torch.float32, device=self.device).unsqueeze(0) | |
| h_next = float(self.cbf_net(x_next_t).item()) | |
| score = self.calibrator.compute_nonconformity_score( | |
| h_curr=self._last_h, | |
| h_next=h_next, | |
| Lf_h=self._last_Lf, | |
| Lg_h=self._last_Lg, | |
| u_executed=self._last_u, | |
| dt=dt, | |
| ) | |
| self.calibrator.update(score=score, h_val=self._last_h) | |
| # 2. Compute drift f(x) and control matrix g(x) | |
| f_val = self.system.f(x_np) | |
| g_val = self.system.g(x_np) | |
| # 3. Evaluate Neural CBF Lie derivatives | |
| x_t = torch.tensor(x_np, dtype=torch.float32, device=self.device) | |
| f_t = torch.tensor(f_val, dtype=torch.float32, device=self.device) | |
| g_t = torch.tensor(g_val, dtype=torch.float32, device=self.device) | |
| h_val_t, grad_h = self.cbf_net.compute_h_and_jacobian(x_t) | |
| h_val = float(h_val_t.detach().item()) | |
| Lf_h = float(torch.dot(grad_h, f_t).detach().item()) | |
| Lg_h = (grad_h @ g_t).detach().cpu().numpy() | |
| # 4. Get active conformal tightening margin | |
| gamma_t = self.calibrator.get_current_margin() | |
| # 5. Solve convex QP | |
| u_safe, qp_info = self.qp_filter.filter( | |
| u_nominal=u_nom_np, | |
| h_val=h_val, | |
| Lf_h=Lf_h, | |
| Lg_h=Lg_h, | |
| gamma=gamma_t, | |
| ) | |
| # Cache step for next conformal update | |
| self._last_state = x_np.copy() | |
| self._last_h = h_val | |
| self._last_u = u_safe.copy() | |
| self._last_Lf = Lf_h | |
| self._last_Lg = Lg_h.copy() | |
| info = { | |
| "h_val": h_val, | |
| "gamma_t": gamma_t, | |
| "effective_h": h_val - gamma_t, | |
| "solve_time_ms": qp_info.get("solve_time_ms", 0.0), | |
| "qp_slack": qp_info.get("slack", 0.0), | |
| "status": qp_info.get("status", "OPTIMAL"), | |
| "safety_certified": bool(h_val >= 0.0), | |
| } | |
| return u_safe, info | |