""" Compact Neural Control Barrier Function (Neural CBF) Network Designed for formal verification tractability and rapid 100+ Hz closed-loop inference. """ from typing import Tuple, List, Optional import torch import torch.nn as nn class NeuralCBF(nn.Module): """ Compact MLP representing scalar barrier certificate h_theta(x). h_theta(x) >= 0 defines the certified safe forward-invariant set. """ def __init__( self, state_dim: int, hidden_dims: List[int] = [64, 64], activation: str = "tanh", ): super().__init__() self.state_dim = state_dim # Choose smooth activations for differentiable Lie derivatives if activation.lower() == "tanh": act_fn = nn.Tanh elif activation.lower() == "silu": act_fn = nn.SiLU elif activation.lower() == "relu": act_fn = nn.ReLU else: raise ValueError(f"Unsupported activation: {activation}") layers = [] prev_dim = state_dim for h_dim in hidden_dims: layers.append(nn.Linear(prev_dim, h_dim)) layers.append(act_fn()) prev_dim = h_dim layers.append(nn.Linear(prev_dim, 1)) self.net = nn.Sequential(*layers) # Initialize final layer weights small for smooth initial barrier with torch.no_grad(): self.net[-1].weight.data.normal_(0.0, 0.05) self.net[-1].bias.data.fill_(0.0) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Forward evaluation: returns h_theta(x) of shape (batch, 1) or scalar. """ return self.net(x) def compute_h_and_jacobian(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Computes barrier value h_theta(x) and its gradient / Jacobian nabla_x h_theta(x). Args: x: Tensor of shape (state_dim,) or (batch, state_dim) Returns: h_val: Tensor of shape (1,) or (batch, 1) grad_h: Tensor of shape (state_dim,) or (batch, state_dim) """ if x.dim() == 1: x_in = x.unsqueeze(0).requires_grad_(True) h = self.net(x_in) grad_h = torch.autograd.grad( outputs=h, inputs=x_in, grad_outputs=torch.ones_like(h), create_graph=True, retain_graph=True, )[0].squeeze(0) return h.squeeze(0), grad_h else: x_in = x.clone().requires_grad_(True) h = self.net(x_in) grad_h = torch.autograd.grad( outputs=h, inputs=x_in, grad_outputs=torch.ones_like(h), create_graph=True, retain_graph=True, )[0] return h, grad_h def lie_derivatives( self, x: torch.Tensor, f_val: torch.Tensor, g_val: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor]: """ Computes Lie derivatives: L_f h(x) = nabla_x h(x)^T * f(x) L_g h(x) = nabla_x h(x)^T * g(x) Args: x: (state_dim,) f_val: (state_dim,) g_val: (state_dim, control_dim) """ _, grad_h = self.compute_h_and_jacobian(x) Lf_h = torch.dot(grad_h, f_val) Lg_h = grad_h @ g_val return Lf_h, Lg_h