Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions act/front_end/specs.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,17 @@ def __post_init__(self) -> None:
if self.center is not None and self.eps is not None:
self.eps = self._eps_like(self.center)

self.lb, self.ub = self.materialize_box_seed()
# Export the same explicit token selection checked by this wrapper.
self.perturbed_positions = self._embedding_position_mask()
elif self.kind == InKind.LINF_BALL and self.center is not None and self.eps is not None:
if isinstance(self.eps, torch.Tensor):
eps_t = self.eps.to(device=self.center.device, dtype=self.center.dtype)
else:
eps_t = self.center.new_tensor(self.eps)
self.lb = self.center - eps_t
self.ub = self.center + eps_t

def materialize_box_seed(self) -> tuple[torch.Tensor, torch.Tensor]:
"""Materialize the box seed used by interval and LP back ends.

Expand Down Expand Up @@ -380,6 +391,151 @@ def input_geometry(self) -> InputGeometry:
center, eps, mask = center.unsqueeze(0), eps.unsqueeze(0), mask.unsqueeze(0)
return InputGeometry(center, eps, mask, float(self.p_norm.item()))

def encode_linear(self) -> dict[str, Any]:
"""Encode this input constraint as parameter dictionaries for ACT layers.

The arguments mirror :meth:`OutputSpec.encode_linear` for API
consistency. Input parameters are already shaped by the spec, so B
and n_out do not change their layout.
"""
params: dict[str, torch.Tensor | str | int] = {"kind": self.kind}
for name in ("lb", "ub", "center", "A", "b", "eps"):
val = getattr(self, name, None)
if isinstance(val, torch.Tensor):
params[name] = val
if self.kind == InKind.LP_EMBEDDING:
for name in ("p_norm", "perturbed_positions"):
val = getattr(self, name, None)
if not isinstance(val, torch.Tensor):
raise ValueError(f"LP_EMBEDDING requires normalized {name}")
params[name] = val
center = params.get("center")
if not isinstance(center, torch.Tensor):
raise ValueError("LP_EMBEDDING requires center")
# Preserve the embedding axis before bounds are flattened.
params["embed_dim"] = center.shape[-1]
return params

@staticmethod
def _gather_rows(value: torch.Tensor, rows: torch.Tensor, batch_size: int, name: str) -> torch.Tensor:
"""Align a row-indexed spec tensor with candidate batch lanes."""
if value.shape[0] == 1:
return value.expand(batch_size, *value.shape[1:])
value_rows = rows.to(device=value.device)
if value_rows.numel() and int(value_rows.max().item()) >= value.shape[0]:
raise IndexError(
f"InputSpec rows out of range for {name}: "
f"max={int(value_rows.max().item())} >= {value.shape[0]} rows"
)
return value.index_select(0, value_rows)

def satisfied(
self,
x: torch.Tensor,
rows: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, str]:
"""Return per-lane membership of candidate inputs in this spec."""
from act.util.counterexample import input_constraint_satisfied

batch_size = x.shape[0]

if rows is None:
rows = torch.arange(batch_size, device=x.device)
else:
rows = rows.to(device=x.device, dtype=torch.long)
if rows.dim() != 1 or rows.numel() != batch_size:
raise ValueError(f"InputSpec rows must have shape ({batch_size},), got {tuple(rows.shape)}")
if rows.numel() and bool((rows < 0).any()):
raise IndexError("InputSpec rows must be non-negative")

if self.kind == InKind.BOX:
lb_buffer, ub_buffer = self.lb, self.ub
if not isinstance(lb_buffer, torch.Tensor) or not isinstance(
ub_buffer, torch.Tensor
):
return (x, torch.full((batch_size,), True), "⚠️ INPUT BOX: Missing lb/ub")

satisfied = input_constraint_satisfied(x, self.kind, {
"lb": self._gather_rows(lb_buffer, rows, batch_size, "lb"),
"ub": self._gather_rows(ub_buffer, rows, batch_size, "ub"),
})
n_ok = satisfied.sum().item()
explanation = f"✅ INPUT BOX: {n_ok}/{batch_size} satisfied"

# Always return tensor (unified output format)
return (x, satisfied, explanation)

elif self.kind == InKind.LINF_BALL:
center_buffer, eps_buffer = self.center, self.eps
if not isinstance(center_buffer, torch.Tensor) or not isinstance(
eps_buffer, torch.Tensor
):
return (x, torch.full((batch_size,), True), "⚠️ INPUT L∞: Missing center/eps")

center = self._gather_rows(
center_buffer, rows, batch_size, "center"
)

eps = self._gather_rows(
eps_buffer, rows, batch_size, "eps"
).reshape(batch_size, *([1] * (x.dim() - 1)))
satisfied = input_constraint_satisfied(
x, self.kind, {"lb": center - eps, "ub": center + eps}
)

n_ok = satisfied.sum().item()
explanation = f"✅ INPUT L∞: {n_ok}/{batch_size} satisfied"

# Always return tensor (unified output format)
return (x, satisfied, explanation)

elif self.kind == InKind.LP_EMBEDDING:
center_buffer, eps_buffer, norm_buffer = self.center, self.eps, self.p_norm
mask_buffer = self.perturbed_positions
if not isinstance(center_buffer, torch.Tensor) or not isinstance(
eps_buffer, torch.Tensor
) or not isinstance(norm_buffer, torch.Tensor) or not isinstance(
mask_buffer, torch.Tensor
):
raise ValueError("LP_EMBEDDING requires normalized input parameters")

geometry = InputGeometry(
self._gather_rows(center_buffer, rows, batch_size, "center"),
self._gather_rows(eps_buffer, rows, batch_size, "eps"),
self._gather_rows(mask_buffer, rows, batch_size, "perturbed_positions"),
float(norm_buffer.item()),
)
satisfied = input_constraint_satisfied(x, self.kind, {}, geometry=geometry)
n_ok = satisfied.sum().item()
explanation = f"✅ INPUT LP_EMBEDDING: {n_ok}/{batch_size} satisfied"
return (x, satisfied, explanation)

elif self.kind == InKind.LIN_POLY:
A_buffer, b_buffer = self.A, self.b
if not isinstance(A_buffer, torch.Tensor) or not isinstance(
b_buffer, torch.Tensor
):
return (x, torch.full((batch_size,), True), "⚠️ INPUT LIN_POLY: Missing A/b")

if A_buffer.dim() == 3:
A_buffer = self._gather_rows(A_buffer, rows, batch_size, "A")
b_buffer = self._gather_rows(b_buffer, rows, batch_size, "b")
params = {"A": A_buffer, "b": b_buffer}
if isinstance(self.lb, torch.Tensor) and isinstance(self.ub, torch.Tensor):
params["lb"] = self._gather_rows(self.lb, rows, batch_size, "lb")
params["ub"] = self._gather_rows(self.ub, rows, batch_size, "ub")
satisfied = input_constraint_satisfied(x, self.kind, params)

# Unified explanation format (consistent across all batch sizes)
n_ok = satisfied.sum().item()
explanation = f"✅ INPUT LIN_POLY: {n_ok}/{batch_size} satisfied"

# Always return tensor (unified output format)
return (x, satisfied, explanation)

else:
return (x, torch.full((batch_size,), True), f"⚠️ INPUT: Unknown kind {self.kind}")


def normalize_input_geometry(
params: Mapping[str, ScalarTensor | str | Sequence[int] | None],
Expand Down
Loading
Loading