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
22 changes: 13 additions & 9 deletions act/front_end/verifiable_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,14 @@ class VerifiableModel(nn.Module):
# Class-level strict mode setting (shared across all instances)
_strict_mode: bool = False

def __init__(self, *, input_layer, input_spec, model, output_spec):
def __init__(
self,
*,
input_layer: InputLayer,
input_spec: InputSpecLayer,
model: nn.Module,
output_spec: OutputSpecLayer
):
super().__init__()
self.input_layer = input_layer
self.input_spec = input_spec
Expand Down Expand Up @@ -403,9 +410,9 @@ class InputSpecLayer(nn.Module):
Forward:
x (N, ...) → (x, satisfied (N,), explanation str)
"""
def __init__(self, spec: Optional[InputSpec] = None, **kwargs):
def __init__(self, spec: InputSpec):
super().__init__()
self.spec = spec or InputSpec(**kwargs)
self.spec = spec
self.kind = self.spec.kind
positions = self.spec.perturbed_positions

Expand Down Expand Up @@ -542,9 +549,6 @@ 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)
Expand Down Expand Up @@ -665,9 +669,9 @@ class OutputSpecLayer(nn.Module):
Forward:
y (N, ...) → (y, satisfied (N,), explanation str)
"""
def __init__(self, spec: Optional[OutputSpec] = None, **kwargs):
def __init__(self, spec: OutputSpec):
super().__init__()
self.spec = spec or OutputSpec(**kwargs)
self.spec = spec
self.kind = self.spec.kind
self._validate_schema()

Expand Down Expand Up @@ -735,6 +739,6 @@ def forward(self, y: torch.Tensor):
violated, _severity = output_violations(y, self.spec)
satisfied = ~violated
n_ok = satisfied.sum().item()
kind_label = self.spec.kind.removesuffix("_ROBUST")
kind_label = self.kind.removesuffix("_ROBUST")
explanation = f"✅ OUTPUT {kind_label}: {n_ok}/{batch_size} satisfied"
return (y, satisfied, explanation)
61 changes: 27 additions & 34 deletions act/pipeline/fuzzing/actfuzzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,33 +9,38 @@
"""

from __future__ import annotations
from dataclasses import dataclass, field, replace
from typing import List, Dict, Optional, Tuple, Any, cast

import json
import os
import time
import json
import torch
import torch.nn as nn
from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

import torch

from act.front_end.specs import InputSpec, OutputSpec
from act.front_end.spec_creator_base import LabeledInputTensor
from act.front_end.verifiable_model import (
InputLayer,
InputSpecLayer,
OutputSpecLayer,
VerifiableModel,
)
from act.pipeline.fuzzing.mutations import MUTATION_STRATEGIES, PERTURB_MODES, MutationEngine
from act.pipeline.fuzzing.coverage import CoverageTracker
from act.pipeline.fuzzing.corpus import SELECTION_STRATEGIES, SeedCorpus, FuzzingSeed
from act.front_end.verifiable_model import VerifiableModel
from act.pipeline.fuzzing.checker import Counterexample, PropertyChecker
from act.pipeline.fuzzing.corpus import SELECTION_STRATEGIES, FuzzingSeed, SeedCorpus
from act.pipeline.fuzzing.coverage import CoverageTracker
from act.pipeline.fuzzing.mutations import (
MUTATION_STRATEGIES,
PERTURB_MODES,
MutationEngine,
)
from act.pipeline.gui import act_gui as _gui
from act.pipeline.gui.act_gui import Option, validate_changes
from act.pipeline.gui.fuzzer_gui import FuzzConfigChange, FuzzControl, FuzzEnd, FuzzStart, FuzzStep
from act.util.path_config import get_pipeline_log_dir
from act.pipeline.gui.fuzzer_gui import (
FuzzConfigChange,
FuzzControl,
FuzzEnd,
FuzzStart,
FuzzStep,
)
from act.util.device_manager import get_default_device
from act.util.format_utils import rule
from act.util.path_config import get_pipeline_log_dir


@dataclass
Expand Down Expand Up @@ -281,7 +286,7 @@ def __init__(
1. Load config → from_yaml() or provided FuzzingConfig
2. Get device from device_manager → get_default_device()
3. Use wrapped model directly → self.model (no spec layer stripping)
4. Extract specs → _extract_spec(InputSpecLayer), _extract_spec(OutputSpecLayer)
4. Extract input and output specs directly from self.model
5. Determine batch size → from InputSpec bounds shape[0] (model synthesis N)
6. Initialize components → MutationEngine, CoverageTracker, PropertyChecker, SeedCorpus
7. Setup tracer → ExecutionTracer (if trace_level > 0)
Expand All @@ -297,15 +302,10 @@ def __init__(
)
self.model = wrapped_model.to(self.device)

# Extract specs for MutationEngine (projection) and PropertyChecker (violation detection).
self.input_spec = cast(Optional[InputSpec], self._extract_spec(InputSpecLayer))
self.output_spec = cast(Optional[OutputSpec], self._extract_spec(OutputSpecLayer))
self.input_spec = self.model.input_spec.spec
self.output_spec = self.model.output_spec.spec

input_layer = next(
(layer for layer in self.model.children() if isinstance(layer, InputLayer)),
None,
)
assert input_layer is not None, "ACTFuzzer requires an InputLayer"
input_layer = self.model.input_layer
assert initial_seeds, "ACTFuzzer requires at least one initial seed"
assert all(seed.tensor.shape[0] == 1 for seed in initial_seeds), (
"Each initial_seeds[i] must represent exactly one spec row"
Expand All @@ -326,7 +326,7 @@ def __init__(
# Batch size is determined by model synthesis (number of VNNLib instances).
self.batch_size = (
self.input_spec.lb.shape[0]
if self.input_spec and self.input_spec.lb is not None
if self.input_spec.lb is not None
else len(initial_seeds)
)

Expand Down Expand Up @@ -399,13 +399,6 @@ def _get_trace_ext(self) -> str:
"""Get file extension for trace storage."""
return {"hdf5": "h5", "json": "json"}[self.config.trace_storage]

def _extract_spec(self, layer_type) -> Optional[InputSpec | OutputSpec]:
"""Extract spec from wrapper layer by type."""
for layer in self.model.children():
if isinstance(layer, layer_type):
return cast(InputSpec | OutputSpec, cast(object, layer.spec))
return None

def fuzz(self) -> FuzzingReport:
"""
Main fuzzing loop.
Expand Down
5 changes: 1 addition & 4 deletions act/pipeline/fuzzing/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ class PropertyChecker:
>>> # violations is List[Counterexample | None] of length B
"""

def __init__(self, output_spec: Optional[OutputSpec]):
def __init__(self, output_spec: OutputSpec):
"""Initialize property checker."""
self.spec = output_spec
self.infeasible_candidates = 0
Expand All @@ -139,9 +139,6 @@ def check(
Returns:
Tuple of (violations_mask BoolTensor[B], List[Counterexample] for violations only)
"""
if self.spec is None:
raise ValueError("PropertyChecker requires an OutputSpec")

input_satisfied = input_satisfied.to(
device=outputs.device, dtype=torch.bool
).reshape(-1)
Expand Down
43 changes: 13 additions & 30 deletions act/pipeline/fuzzing/mutations.py
Original file line number Diff line number Diff line change
Expand Up @@ -645,14 +645,16 @@ class MutationEngine:
>>> activations = engine.get_activation_map()
"""

def __init__(self,
model: nn.Module,
input_spec: Optional[InputSpec],
weights: Dict[str, float],
perturb_mode: str = "fixed",
perturb_scale: float = 0.1,
pgd_restarts: int = 1,
pgd_restarts_binarized: int = 1):
def __init__(
self,
model: VerifiableModel,
input_spec: InputSpec | None,
weights: dict[str, float],
perturb_mode: str = "fixed",
perturb_scale: float = 0.1,
pgd_restarts: int = 1,
pgd_restarts_binarized: int = 1
):
"""
Initialize mutation engine.

Expand All @@ -667,10 +669,6 @@ def __init__(self,
pgd_restarts: PGD random starts per mutation.
pgd_restarts_binarized: PGD random starts per mutation once sign
estimators are installed.

Raises:
TypeError: If ``model`` is not a VerifiableModel.
ValueError: If ``model`` carries no OutputSpec, or weights are invalid.
"""
self.model = model
self.attack_model, self.output_spec, self.logit_sink = (
Expand Down Expand Up @@ -744,8 +742,8 @@ def set_pgd_restarts(self, restarts: int, restarts_binarized: int) -> None:

@staticmethod
def _resolve_attack_target(
model: nn.Module,
) -> tuple[nn.Module, OutputSpec, Optional[Dict[str, torch.Tensor]]]:
model: VerifiableModel,
) -> tuple[nn.Module, OutputSpec, dict[str, torch.Tensor] | None]:
"""Split a wrapped model into the network to attack and the property to attack it with.

The gradient strategies attack the INNER network rather than the
Expand All @@ -772,24 +770,9 @@ def _resolve_attack_target(
Returns:
Tuple of (inner network returning logits, output property to
ascend, pre-softmax logit sink or None).

Raises:
TypeError: If ``model`` is not a VerifiableModel, so no inner network
and no property can be identified.
ValueError: If the wrapper carries no OutputSpec; the gradient
strategies have no objective without one.
"""
if not isinstance(model, VerifiableModel):
raise TypeError(
f"MutationEngine requires a VerifiableModel to source the attack "
f"objective, got {type(model).__name__}."
)
output_spec = model.output_spec.spec
if output_spec is None:
raise ValueError(
"MutationEngine requires an OutputSpec: the gradient strategies "
"ascend its violation severity."
)

inner = model.model
if output_spec.kind not in LOGIT_GUIDED_KINDS:
return inner, output_spec, None
Expand Down
Loading