File size: 3,438 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 | """
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
|