diff --git a/act/front_end/specs.py b/act/front_end/specs.py index efdfb2e7f..24bb36fe8 100644 --- a/act/front_end/specs.py +++ b/act/front_end/specs.py @@ -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. @@ -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], diff --git a/act/front_end/verifiable_model.py b/act/front_end/verifiable_model.py index a9bf410b6..e08f20ba1 100644 --- a/act/front_end/verifiable_model.py +++ b/act/front_end/verifiable_model.py @@ -79,11 +79,11 @@ from typing import Dict, Any, Optional, List, Tuple, Union # Import ACT components -from act.front_end.specs import InputGeometry, InputSpec, OutputSpec, InKind, OutKind +from act.front_end.specs import InputSpec, OutputSpec, InKind, OutKind from act.front_end.spec_creator_base import LabeledInputTensor from act.back_end.layer_schema import LayerKind, REGISTRY from act.back_end.layer_util import create_layer -from act.util.counterexample import input_constraint_satisfied, output_violations +from act.util.counterexample import output_violations class VerifiableModel(nn.Module): @@ -406,78 +406,21 @@ class InputSpecLayer(nn.Module): def __init__(self, spec: Optional[InputSpec] = None, **kwargs): super().__init__() self.spec = spec or InputSpec(**kwargs) - self.kind = self.spec.kind - positions = self.spec.perturbed_positions - - if self.kind == InKind.LP_EMBEDDING: - self.spec.lb, self.spec.ub = self.spec.materialize_box_seed() - # Export the same explicit token selection checked by this wrapper. - positions = self.spec._embedding_position_mask() - elif self.kind == InKind.LINF_BALL and self.spec.center is not None and self.spec.eps is not None: - eps = self.spec.eps - if isinstance(eps, torch.Tensor): - eps_t = eps.to(device=self.spec.center.device, dtype=self.spec.center.dtype) - else: - eps_t = self.spec.center.new_tensor(eps) - self.spec.lb = self.spec.center - eps_t - self.spec.ub = self.spec.center + eps_t - - # Register eps as buffer for device mobility - if isinstance(self.spec.eps, torch.Tensor): - self.register_buffer("eps", self.spec.eps) - else: - self.eps = None - - if isinstance(self.spec.p_norm, torch.Tensor): - self.register_buffer("p_norm", self.spec.p_norm) - else: - self.p_norm = None - - if isinstance(positions, torch.Tensor): - self.register_buffer("perturbed_positions", positions) - else: - self.perturbed_positions = None - - # Register tensor fields as buffers so .to(device) works - for name in ("lb", "ub", "center", "A", "b"): - val = getattr(self.spec, name, None) - if isinstance(val, torch.Tensor): - self.register_buffer(name, val) - else: - setattr(self, name, None) + self.kind = self.spec.kind self._validate_schema() - def _act_params(self) -> dict[str, torch.Tensor | str | int]: - """Use one parameter layout for schema checks and ACT emission.""" - 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 - def _validate_schema(self): - """Validate parameters against INPUT_SPEC layer schema""" - schema = REGISTRY[LayerKind.INPUT_SPEC.value] - params = self._act_params() - # Check schema compliance - for key in schema["params_required"]: - if key not in params: - raise ValueError(f"InputSpecLayer missing required param: {key}") - for key in params: - if key not in schema["params_required"] + schema["params_optional"]: - raise ValueError(f"InputSpecLayer has unknown param: {key}") + """Pre-flight kind validation; full INPUT_SPEC-layer schema is + enforced at ``to_act_layers()`` time via ``create_layer``. + """ + supported = ( + InKind.BOX, InKind.LINF_BALL, InKind.LIN_POLY, InKind.LP_EMBEDDING, + ) + if self.kind not in supported: + raise ValueError( + f"InputSpecLayer: unsupported kind {self.kind!r}; " + f"expected one of {supported}" + ) def to_act_layers( self, @@ -487,49 +430,31 @@ def to_act_layers( ) -> Tuple[List, List[int]]: """Convert to ACT Layer(s) - INPUT_SPEC doesn't create new vars. - ``B`` is accepted for signature parity with ``OutputSpecLayer`` so - callers can pass the batch dim uniformly; currently unused because - ``InputSpec`` tensors are already batched at construction time - (lb/ub/center carry the leading B dim from the wrapped tensors). + Pass the batch size, input dimension, and default device and dtype to + ``InputSpec.encode_linear``. The spec's tensors already carry their + input and batch dimensions. """ - del B - params = self._act_params() + params = self.spec.encode_linear() + specs = [params] if self.kind == InKind.LIN_POLY and "lb" in params and "ub" in params: # A polytope stored with its enclosing box: the BOX layer seeds the # analysis (interval domains cannot use A·x <= b) and the LIN_POLY # layer keeps the relations for LP back ends and counterexample checks. specs = [{"kind": InKind.BOX, "lb": params.pop("lb"), "ub": params.pop("ub")}, params] + layers = [ create_layer( id=layer_id_start + k, kind=LayerKind.INPUT_SPEC.value, - params=spec, + params=params, in_vars=in_vars, out_vars=in_vars, ) - for k, spec in enumerate(specs) + for k, params in enumerate(specs) ] return layers, in_vars - @staticmethod - def _gather_rows( - value: torch.Tensor, - rows: torch.Tensor, - batch_size: int, - name: str, - ) -> torch.Tensor: - """Align a row-indexed spec tensor with the current 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"InputSpecLayer 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 forward( self, x: torch.Tensor, @@ -542,109 +467,11 @@ def forward( Tuple of (tensor, satisfied, explanation) - For batch=1 andbatch>1: satisfied is (batch,) bool tensor """ - if self.spec is None: - return (x, True, "✅ INPUT: No constraints") - 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"InputSpecLayer rows must have shape ({batch_size},), " - f"got {tuple(rows.shape)}" - ) - if rows.numel() and bool((rows < 0).any()): - raise IndexError("InputSpecLayer 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, 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, 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, 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, True, f"⚠️ INPUT: Unknown kind {self.kind}") + + x, satisfied, explanation = self.spec.satisfied(x, rows) + explanation = f"✅ INPUT {self.kind}: {satisfied.sum().item()}/{batch_size} satisfied" + return (x, satisfied, explanation) class OutputSpecLayer(nn.Module):