Download src/verifier/cegis.py from codewithyug/certified-safe-neural-control: direct link, hf CLI and curl.
- Browser
- Download file 3.84 kB
-
https://huggingface.co/codewithyug/certified-safe-neural-control/resolve/main/src/verifier/cegis.py
- Command line
-
hf download hf://codewithyug/certified-safe-neural-control/src/verifier/cegis.py
-
curl -L -o cegis.py https://huggingface.co/codewithyug/certified-safe-neural-control/resolve/main/src/verifier/cegis.py
3.84 kB
| """ | |
| Counterexample-Guided Inductive Synthesis (CEGIS) for Neural CBFs | |
| Automatically extracts verified counterexamples from the formal verifier and retrains | |
| the barrier network to guarantee regional forward invariance. | |
| """ | |
| from typing import Dict, Any | |
| import numpy as np | |
| import torch | |
| import torch.optim as optim | |
| from src.dynamics.base import ControlAffineSystem | |
| from src.cbf.network import NeuralCBF | |
| from src.cbf.loss import CBFLoss | |
| from src.verifier.symbolic_adapter import RegionalCBFVerifier | |
| class CEGISSynthesizer: | |
| """ | |
| CEGIS loop orchestrating iterative formal verification and retraining. | |
| """ | |
| def __init__( | |
| self, | |
| system: ControlAffineSystem, | |
| cbf_net: NeuralCBF, | |
| loss_fn: CBFLoss, | |
| alpha_cbf: float = 1.0, | |
| ): | |
| self.system = system | |
| self.cbf_net = cbf_net | |
| self.loss_fn = loss_fn | |
| self.verifier = RegionalCBFVerifier(system, cbf_net, alpha_cbf=alpha_cbf) | |
| def synthesize( | |
| self, | |
| domain_min: np.ndarray, | |
| domain_max: np.ndarray, | |
| x_safe_base: torch.Tensor, | |
| x_unsafe_base: torch.Tensor, | |
| max_cegis_iters: int = 5, | |
| target_coverage: float = 0.95, | |
| ) -> Dict[str, Any]: | |
| """ | |
| Executes CEGIS synthesis loop until target domain coverage is achieved. | |
| """ | |
| optimizer = optim.Adam(self.cbf_net.parameters(), lr=5e-4) | |
| cegis_history = [] | |
| accumulated_cex = [] | |
| for iteration in range(1, max_cegis_iters + 1): | |
| # 1. Run Verification Pass | |
| verif_res = self.verifier.verify_domain( | |
| domain_min=domain_min, | |
| domain_max=domain_max, | |
| max_boxes=300, | |
| time_limit_sec=15.0, | |
| ) | |
| cov = verif_res["verified_volume_ratio"] | |
| cex_list = verif_res["counterexamples"] | |
| print( | |
| f"[CEGIS Iter {iteration}] Verified Volume: {cov * 100:.2f}% | " | |
| f"New Counterexamples: {len(cex_list)} | Status: {verif_res['status']}" | |
| ) | |
| cegis_history.append({ | |
| "iteration": iteration, | |
| "coverage": cov, | |
| "cex_count": len(cex_list), | |
| "elapsed": verif_res["elapsed_seconds"], | |
| }) | |
| if cov >= target_coverage and len(cex_list) == 0: | |
| print(f"[+] CEGIS Converged: Reached {cov*100:.2f}% verified volume!") | |
| break | |
| if len(cex_list) > 0: | |
| accumulated_cex.extend(cex_list) | |
| # 2. Retrain with accumulated counterexamples | |
| if len(accumulated_cex) > 0: | |
| x_cex_tensor = torch.tensor(np.array(accumulated_cex[-200:]), dtype=torch.float32) | |
| f_cex_list = [self.system.f(s) for s in x_cex_tensor.numpy()] | |
| g_cex_list = [self.system.g(s) for s in x_cex_tensor.numpy()] | |
| f_b = torch.tensor(np.array(f_cex_list), dtype=torch.float32) | |
| g_b = torch.tensor(np.array(g_cex_list), dtype=torch.float32) | |
| u_nom = torch.zeros((len(x_cex_tensor), self.system.control_dim), dtype=torch.float32) | |
| self.cbf_net.train() | |
| for _ in range(25): # Fine-tune epochs | |
| optimizer.zero_grad() | |
| loss_dict = self.loss_fn( | |
| model=self.cbf_net, | |
| x_safe=x_safe_base[:128], | |
| x_unsafe=x_unsafe_base[:128], | |
| x_boundary=x_cex_tensor, | |
| f_boundary=f_b, | |
| g_boundary=g_b, | |
| u_nominal=u_nom, | |
| ) | |
| loss_dict["total_loss"].backward() | |
| optimizer.step() | |
| return {"history": cegis_history, "final_coverage": cov} | |