From 1263488e83fc106b26fe4a279559303dd11c5320 Mon Sep 17 00:00:00 2001 From: hanyuone Date: Wed, 2 Dec 2026 11:06:10 +1100 Subject: [PATCH 1/6] fix: add typehints, remove unnecessary type checks --- act/front_end/verifiable_model.py | 15 ++++++--------- act/pipeline/fuzzing/checker.py | 5 +---- act/pipeline/fuzzing/mutations.py | 27 +++++++++------------------ 3 files changed, 16 insertions(+), 31 deletions(-) diff --git a/act/front_end/verifiable_model.py b/act/front_end/verifiable_model.py index a9bf410b6..d61aa7929 100644 --- a/act/front_end/verifiable_model.py +++ b/act/front_end/verifiable_model.py @@ -118,7 +118,7 @@ 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 @@ -403,9 +403,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 @@ -542,9 +542,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) @@ -665,9 +662,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() @@ -735,6 +732,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) diff --git a/act/pipeline/fuzzing/checker.py b/act/pipeline/fuzzing/checker.py index f8317ac5a..b985948c3 100644 --- a/act/pipeline/fuzzing/checker.py +++ b/act/pipeline/fuzzing/checker.py @@ -118,7 +118,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 @@ -140,9 +140,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 = getattr(outputs, INPUT_FEASIBILITY_ATTR, None) if not isinstance(input_satisfied, torch.Tensor): raise RuntimeError( diff --git a/act/pipeline/fuzzing/mutations.py b/act/pipeline/fuzzing/mutations.py index 1bdc0b26a..487a6acd6 100644 --- a/act/pipeline/fuzzing/mutations.py +++ b/act/pipeline/fuzzing/mutations.py @@ -181,7 +181,7 @@ class MutationStrategy(ABC): @abstractmethod def mutate(self, input_tensor: torch.Tensor, - model: nn.Module, + model: VerifiableModel, activations: Optional[Dict[str, torch.Tensor]] = None, rows: Optional[torch.Tensor] = None ) -> torch.Tensor: @@ -244,7 +244,7 @@ def __init__( self.logit_sink = logit_sink self.sign_stes: List[SignSTE] = [] - def _attack_output(self, x: torch.Tensor, model: nn.Module) -> torch.Tensor: + def _attack_output(self, x: torch.Tensor, model: VerifiableModel) -> torch.Tensor: """Forward ``x`` and return the tensor the objective scores.""" if self.logit_sink is None: return model(x) @@ -255,7 +255,7 @@ def _attack_output(self, x: torch.Tensor, model: nn.Module) -> torch.Tensor: def _severity( self, x: torch.Tensor, - model: nn.Module, + model: VerifiableModel, rows: Optional[torch.Tensor], ) -> torch.Tensor: """Per-lane violation severity of ``x`` under the attack objective.""" @@ -264,7 +264,7 @@ def _severity( def _severity_sum( self, x: torch.Tensor, - model: nn.Module, + model: VerifiableModel, rows: Optional[torch.Tensor], ) -> torch.Tensor: """Forward ``x`` and return the batch's total violation severity. @@ -322,7 +322,7 @@ def _boundary_proximity(self) -> Union[torch.Tensor, float]: def input_gradient( self, x: torch.Tensor, - model: nn.Module, + model: VerifiableModel, rows: Optional[torch.Tensor], ) -> torch.Tensor: """Gradient of the batch's total severity w.r.t. ``x``. @@ -445,7 +445,7 @@ def _ascend( x_low: torch.Tensor, x_high: torch.Tensor, step_size: float, - model: nn.Module, + model: VerifiableModel, rows: Optional[torch.Tensor], ) -> torch.Tensor: """Run one restart: random start, then projected sign-gradient ascent.""" @@ -645,7 +645,7 @@ class MutationEngine: """ def __init__(self, - model: nn.Module, + model: VerifiableModel, input_spec: Optional[InputSpec], weights: Dict[str, float], perturb_mode: str = "fixed", @@ -746,7 +746,7 @@ def set_pgd_restarts(self, restarts: int, restarts_binarized: int) -> None: @staticmethod def _resolve_attack_target( - model: nn.Module, + model: VerifiableModel, ) -> tuple[nn.Module, OutputSpec, Optional[Dict[str, torch.Tensor]]]: """Split a wrapped model into the network to attack and the property to attack it with. @@ -781,17 +781,8 @@ def _resolve_attack_target( 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 From f498a1eccf58d6823233a1df6d414142ce106ee0 Mon Sep 17 00:00:00 2001 From: hanyuone Date: Wed, 2 Dec 2026 11:18:41 +1100 Subject: [PATCH 2/6] fix: revert all VerifiableModel changes where attack model used as input --- act/pipeline/fuzzing/mutations.py | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/act/pipeline/fuzzing/mutations.py b/act/pipeline/fuzzing/mutations.py index 487a6acd6..c076e3790 100644 --- a/act/pipeline/fuzzing/mutations.py +++ b/act/pipeline/fuzzing/mutations.py @@ -181,7 +181,7 @@ class MutationStrategy(ABC): @abstractmethod def mutate(self, input_tensor: torch.Tensor, - model: VerifiableModel, + model: nn.Module, activations: Optional[Dict[str, torch.Tensor]] = None, rows: Optional[torch.Tensor] = None ) -> torch.Tensor: @@ -244,7 +244,7 @@ def __init__( self.logit_sink = logit_sink self.sign_stes: List[SignSTE] = [] - def _attack_output(self, x: torch.Tensor, model: VerifiableModel) -> torch.Tensor: + def _attack_output(self, x: torch.Tensor, model: nn.Module) -> torch.Tensor: """Forward ``x`` and return the tensor the objective scores.""" if self.logit_sink is None: return model(x) @@ -255,7 +255,7 @@ def _attack_output(self, x: torch.Tensor, model: VerifiableModel) -> torch.Tenso def _severity( self, x: torch.Tensor, - model: VerifiableModel, + model: nn.Module, rows: Optional[torch.Tensor], ) -> torch.Tensor: """Per-lane violation severity of ``x`` under the attack objective.""" @@ -264,7 +264,7 @@ def _severity( def _severity_sum( self, x: torch.Tensor, - model: VerifiableModel, + model: nn.Module, rows: Optional[torch.Tensor], ) -> torch.Tensor: """Forward ``x`` and return the batch's total violation severity. @@ -322,7 +322,7 @@ def _boundary_proximity(self) -> Union[torch.Tensor, float]: def input_gradient( self, x: torch.Tensor, - model: VerifiableModel, + model: nn.Module, rows: Optional[torch.Tensor], ) -> torch.Tensor: """Gradient of the batch's total severity w.r.t. ``x``. @@ -445,7 +445,7 @@ def _ascend( x_low: torch.Tensor, x_high: torch.Tensor, step_size: float, - model: VerifiableModel, + model: nn.Module, rows: Optional[torch.Tensor], ) -> torch.Tensor: """Run one restart: random start, then projected sign-gradient ascent.""" @@ -469,7 +469,7 @@ def _ascend( return x_adv.detach() - def mutate(self, input_tensor, model, activations=None, rows=None): + def mutate(self, input_tensor, model: nn.Module, activations=None, rows=None): """Apply PGD mutation. Runs :attr:`restarts` independent random starts and keeps, per lane, @@ -666,10 +666,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 = ( From 9bc8ae337844c0626522eda630395946b8b989b9 Mon Sep 17 00:00:00 2001 From: hanyuone Date: Wed, 2 Dec 2026 11:25:47 +1100 Subject: [PATCH 3/6] fix: remove Optional and Dict from `_resolve_attack_target` --- act/pipeline/fuzzing/mutations.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/act/pipeline/fuzzing/mutations.py b/act/pipeline/fuzzing/mutations.py index d0313143b..73e2c8afd 100644 --- a/act/pipeline/fuzzing/mutations.py +++ b/act/pipeline/fuzzing/mutations.py @@ -741,7 +741,7 @@ def set_pgd_restarts(self, restarts: int, restarts_binarized: int) -> None: @staticmethod def _resolve_attack_target( model: VerifiableModel, - ) -> tuple[nn.Module, OutputSpec, Optional[Dict[str, torch.Tensor]]]: + ) -> 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 From 0d304fda37a6a7404c611358e65ed441c30b0095 Mon Sep 17 00:00:00 2001 From: hanyuone Date: Wed, 2 Dec 2026 15:20:09 +1100 Subject: [PATCH 4/6] style: format edited functions --- act/front_end/verifiable_model.py | 9 ++++++++- act/pipeline/fuzzing/mutations.py | 18 ++++++++++-------- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/act/front_end/verifiable_model.py b/act/front_end/verifiable_model.py index d61aa7929..1d6fbf8da 100644 --- a/act/front_end/verifiable_model.py +++ b/act/front_end/verifiable_model.py @@ -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: InputLayer, input_spec: InputSpecLayer, model: nn.Module, output_spec: OutputSpecLayer): + 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 diff --git a/act/pipeline/fuzzing/mutations.py b/act/pipeline/fuzzing/mutations.py index 73e2c8afd..3586fd65d 100644 --- a/act/pipeline/fuzzing/mutations.py +++ b/act/pipeline/fuzzing/mutations.py @@ -645,14 +645,16 @@ class MutationEngine: >>> activations = engine.get_activation_map() """ - def __init__(self, - model: VerifiableModel, - 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. From 2fd20d463a1277a82b1b6440b17abf6a2bbec146 Mon Sep 17 00:00:00 2001 From: hanyuone Date: Thu, 3 Dec 2026 11:01:47 +1100 Subject: [PATCH 5/6] fix: simplify further typechecks --- act/pipeline/fuzzing/actfuzzer.py | 57 ++++++++++++++----------------- act/pipeline/fuzzing/mutations.py | 8 +---- 2 files changed, 27 insertions(+), 38 deletions(-) diff --git a/act/pipeline/fuzzing/actfuzzer.py b/act/pipeline/fuzzing/actfuzzer.py index 12e16e3f0..ca50a16db 100644 --- a/act/pipeline/fuzzing/actfuzzer.py +++ b/act/pipeline/fuzzing/actfuzzer.py @@ -9,33 +9,40 @@ """ 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.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 @@ -281,7 +288,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) @@ -297,15 +304,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" @@ -326,7 +328,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) ) @@ -399,13 +401,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. diff --git a/act/pipeline/fuzzing/mutations.py b/act/pipeline/fuzzing/mutations.py index 3586fd65d..73cad1602 100644 --- a/act/pipeline/fuzzing/mutations.py +++ b/act/pipeline/fuzzing/mutations.py @@ -470,7 +470,7 @@ def _ascend( return x_adv.detach() - def mutate(self, input_tensor, model: nn.Module, activations=None, rows=None): + def mutate(self, input_tensor, model, activations=None, rows=None): """Apply PGD mutation. Runs :attr:`restarts` independent random starts and keeps, per lane, @@ -770,12 +770,6 @@ 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. """ output_spec = model.output_spec.spec From 5e190094d8f22c7b27cbd0dc2e27d01eb65b7f6e Mon Sep 17 00:00:00 2001 From: hanyuone Date: Thu, 3 Dec 2026 11:08:43 +1100 Subject: [PATCH 6/6] style: simplify imports --- act/pipeline/fuzzing/actfuzzer.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/act/pipeline/fuzzing/actfuzzer.py b/act/pipeline/fuzzing/actfuzzer.py index ca50a16db..216979a52 100644 --- a/act/pipeline/fuzzing/actfuzzer.py +++ b/act/pipeline/fuzzing/actfuzzer.py @@ -20,9 +20,7 @@ import torch from act.front_end.spec_creator_base import LabeledInputTensor -from act.front_end.verifiable_model import ( - VerifiableModel, -) +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