python Copy code
# defence.py
from typing import Any, Dict, List, Type
from art.defences import (
EvasionDetector,
BinaryInputDetector,
BinaryActivationDetector,
SubsetScanningDetector,
PoisonFilteringDefence,
GroundTruthEvaluator,
ActivationDefence,
ClusteringAnalyzer,
ProvenanceDefense,
RONIDefense,
SpectralSignatureDefense,
ClassLabels,
GaussianNoise,
HighConfidence,
Postprocessor,
ReverseSigmoid,
Rounded,
CutMix,
CutMixPyTorch,
CutMixTensorFlowV2,
Cutout,
CutoutPyTorch,
CutoutTensorFlowV2,
FeatureSqueezing,
GaussianAugmentation,
DefenseGAN,
InverseGAN,
JpegCompression,
LabelSmoothing,
Mixup,
MixupPyTorch,
MixupTensorFlowV2,
Mp3Compression,
Mp3CompressionPyTorch,
PixelDefend,
Preprocessor,
Resample,
SpatialSmoothing,
SpatialSmoothingPyTorch,
SpatialSmoothingTensorFlowV2,
ThermometerEncoding,
TotalVarMin,
VideoCompression,
VideoCompressionPyTorch,
Trainer,
AdversarialTrainer,
AdversarialTrainerCertifiedPytorch,
AdversarialTrainerCertifiedIBPPyTorch,
AdversarialTrainerMadryPGD,
AdversarialTrainerFBF,
AdversarialTrainerFBFPyTorch,
AdversarialTrainerTRADES,
AdversarialTrainerTRADESPyTorch,
AdversarialTrainerAWP,
AdversarialTrainerAWPPyTorch,
AdversarialTrainerOAAT,
AdversarialTrainerOAATPyTorch,
DPInstaHideTrainer,
Transformer,
evasion,
poisoning
)
from art.attacks.evasion import (
AdversarialPatch,
AdversarialPatchNumpy,
AdversarialPatchPyTorch,
AdversarialTexturePyTorch,
AutoAttack,
AutoProjectedGradientDescent,
AutoConjugateGradient,
BrendelBethgeAttack,
BoundaryAttack,
CompositeAdversarialAttackPyTorch,
CarliniL2Method,
CarliniLInfMethod,
DeepFool,
DPatch,
RobustDPatch,
ElasticNet,
FastGradientMethod,
GeoDA,
GRAPHITEWhiteboxPyTorch,
HopSkipJump,
BasicIterativeMethod,
MomentumIterativeMethod,
NewtonFool,
OverloadPyTorch,
PixelAttack,
ProjectedGradientDescent,
ProjectedGradientDescentPyTorch,
SaliencyMapMethod,
ShadowAttack,
SpatialTransformation,
SquareAttack,
UniversalPerturbation,
VirtualAdversarialMethod,
Wasserstein,
ZooAttack,
SignOPTAttack,
)
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Type alias for attack and defense classes
AttackType = Type[Any]
DefenseType = Type[Any]
def get_defense_list() -> List[DefenseType]:
"""
Retrieve a list of defense instances from the ART library.
Returns:
List[DefenseType]: A list of instantiated defense classes.
"""
try:
clip_values = (0.0, 1.0) # Adjust based on preprocessing
defense_list = [
JpegCompression(clip_values=clip_values, quality=50),
FeatureSqueezing(bit_depth=1, clip_values=clip_values),
GaussianNoise(),
LabelSmoothing(),
PixelDefend(),
SpatialSmoothing(),
ThermometerEncoding(),
TotalVarMin(),
VideoCompression(clip_values=clip_values, num_frames=5),
DefenseGAN(),
InverseGAN(),
Mixup(alpha=0.2),
CutMix(alpha=0.2),
Cutout(),
GaussianAugmentation(),
ReverseSigmoid(),
Rounded(),
Postprocessor(),
Resample(),
Preprocessor(),
ClassLabels(),
ClusteringAnalyzer(),
GroundTruthEvaluator(),
ActivationDefence(),
SubsetScanningDetector(),
BinaryInputDetector(),
BinaryActivationDetector(),
EvasionDetector(),
PoisonFilteringDefence(),
ProvenanceDefense(),
RONIDefense(),
SpectralSignatureDefense(),
]
logger.info("Defense list created successfully.")
return defense_list
except Exception as e:
logger.error(f"Error creating defense list: {e}")
raise
def get_defense_parameters(defense: DefenseType) -> Dict[str, Any]:
"""
Retrieve default parameters for each defense.
Args:
defense (DefenseType): The defense instance.
Returns:
Dict[str, Any]: Dictionary of parameters.
"""
try:
default_params: Dict[Type[Any], Dict[str, Any]] = {
JpegCompression: {
"clip_values": (0.0, 1.0),
"quality": 50,
},
FeatureSqueezing: {
"bit_depth": 1,
"clip_values": (0.0, 1.0),
},
GaussianNoise: {
"mean": 0.0,
"stddev": 0.1,
},
LabelSmoothing: {
"smoothing": 0.1,
},
PixelDefend: {
"training_epochs": 10,
"batch_size": 128,
},
SpatialSmoothing: {
"window_size": 5,
"channel_index": 3,
},
ThermometerEncoding: {
"num_bins": 64,
},
TotalVarMin: {
"epsilon": 0.1,
},
VideoCompression: {
"clip_values": (0.0, 1.0),
"num_frames": 5,
},
DefenseGAN: {
"grob": "path/to/generator",
},
InverseGAN: {
"grob": "path/to/inverse_generator",
},
Mixup: {
"alpha": 0.2,
},
CutMix: {
"alpha": 0.2,
},
Cutout: {
"num_holes": 1,
"length": 16,
},
GaussianAugmentation: {
"mean": 0.0,
"stddev": 0.1,
},
ReverseSigmoid: {
"gamma": 2.0,
},
Rounded: {
"decimals": 2,
},
Postprocessor: {
"operation": "clip",
},
Resample: {
"new_size": (224, 224),
},
Preprocessor: {
"operation": "normalize",
},
ClassLabels: {
"num_classes": 10,
},
ClusteringAnalyzer: {
"num_clusters": 10,
},
GroundTruthEvaluator: {
"metric": "accuracy",
},
ActivationDefence: {
"activation_layer": "relu",
},
SubsetScanningDetector: {
"subset_size": 100,
},
BinaryInputDetector: {
"threshold": 0.5,
},
BinaryActivationDetector: {
"activation_threshold": 0.5,
},
EvasionDetector: {
"detector_type": "SVM",
},
PoisonFilteringDefence: {
"filtering_rate": 0.1,
},
ProvenanceDefense: {
"provenance_method": "hash",
},
RONIDefense: {
"sensitivity": 0.1,
},
SpectralSignatureDefense: {
"threshold": 0.1,
},
}
defense_class = type(defense)
params = default_params.get(defense_class, {})
logger.info(f"Retrieved parameters for {defense_class.__name__}.")
return params
except Exception as e:
logger.error(f"Error retrieving parameters for defense {type(defense).__name__}: {e}")
raise
def get_all_defenses() -> List[DefenseType]:
"""
Retrieve all defense classes available for testing.
Returns:
List[DefenseType]: List of defense classes.
"""
try:
defense_list = get_defense_list()
logger.info(f"Retrieved {len(defense_list)} defense(s).")
return defense_list
except Exception as e:
logger.error(f"Error retrieving all defenses: {e}")
raise
def get_attack_parameters(attack: AttackType) -> Dict[str, Any]:
"""
Retrieve default parameters for each attack.
Args:
attack (AttackType): The attack class.
Returns:
Dict[str, Any]: Dictionary of parameters.
"""
try:
default_params: Dict[Type[Any], Dict[str, Any]] = {
AdversarialPatch: {
"rotation_max": 22.5,
"scale_min": 0.1,
"scale_max": 1.0,
"learning_rate": 5.0,
"max_iter": 500,
"batch_size": 16,
"patch_shape": (3, 10, 10),
"targeted": True,
"verbose": True,
},
AdversarialPatchNumpy: {
"rotation_max": 22.5,
"scale_min": 0.1,
"scale_max": 1.0,
"learning_rate": 5.0,
"max_iter": 500,
"batch_size": 16,
"patch_shape": (3, 10, 10),
"targeted": True,
"verbose": True,
},
AdversarialPatchPyTorch: {
"rotation_max": 22.5,
"scale_min": 0.1,
"scale_max": 1.0,
"learning_rate": 5.0,
"max_iter": 500,
"batch_size": 16,
"patch_shape": (3, 10, 10),
"targeted": True,
"verbose": True,
},
AdversarialTexturePyTorch: {
"texture": "path/to/texture",
"max_iter": 1000,
"learning_rate": 0.01,
"verbose": True,
},
AutoAttack: {
"norm": "Linf",
"eps": 0.3,
"n_repeats": 2,
"version": "standard",
"device_type": "gpu",
},
AutoProjectedGradientDescent: {
"norm": "Linf",
"eps": 0.3,
"eps_step": 0.1,
"max_iter": 40,
"targeted": False,
"num_random_init": 1,
"batch_size": 16,
"verbose": False,
},
AutoConjugateGradient: {
"norm": "Linf",
"eps": 0.3,
"max_iter": 40,
"targeted": False,
"batch_size": 16,
"verbose": False,
},
BrendelBethgeAttack: {
"confidence": 0.0,
"targeted": False,
"learning_rate": 0.01,
"binary_search_steps": 9,
"max_iterations": 1000,
"initial_const": 1e-2,
"abort_early": True,
"min_accuracy": 0.0,
"verbose": False,
},
BoundaryAttack: {
"max_iter": 10000,
"init_size": 0.1,
"epsilon": 0.01,
"step_size": 0.1,
"max_epsilon": 0.3,
"margin": 0.0,
"targeted": False,
"verbose": False,
},
CompositeAdversarialAttackPyTorch: {
"attacks": [
FastGradientMethod(),
ProjectedGradientDescent(),
],
"params": {},
},
CarliniL2Method: {
"confidence": 0.0,
"learning_rate": 0.01,
"binary_search_steps": 9,
"max_iter": 1000,
"initial_const": 1e-2,
"loss_fn": "cross_entropy",
"verbose": False,
},
CarliniLInfMethod: {
"confidence": 0.0,
"learning_rate": 0.01,
"binary_search_steps": 9,
"max_iter": 1000,
"initial_const": 1e-2,
"loss_fn": "cross_entropy",
"clip_min": 0.0,
"clip_max": 1.0,
"verbose": False,
},
DeepFool: {
"epsilon": 1e-6,
"max_iter": 50,
"num_classes": 10,
"overshoot": 0.02,
"clip_min": 0.0,
"clip_max": 1.0,
"verbose": False,
},
DPatch: {
"target": 0,
"cross_rate": 0.1,
"maxiter": 10,
"num_holes": 1,
"mask_shape": (3, 10, 10),
"targeted": True,
"seed": 42,
"verbose": False,
},
RobustDPatch: {
"target": 0,
"cross_rate": 0.1,
"maxiter": 10,
"num_holes": 1,
"mask_shape": (3, 10, 10),
"targeted": True,
"seed": 42,
"verbose": False,
},
ElasticNet: {
"confidence": 0.0,
"lambda_param": 0.01,
"learning_rate": 0.01,
"max_iter": 1000,
"binary_search_steps": 9,
"initial_const": 1e-2,
"verbose": False,
},
FastGradientMethod: {
"eps": 0.3,
"eps_step": 0.1,
"targeted": False,
"nb_iter": 40,
"ord": 2,
"clip_min": 0.0,
"clip_max": 1.0,
"batch_size": 16,
"verbose": False,
},
GeoDA: {
"distance_metric": "L2",
"nb_candidates": 10,
"max_iter": 1000,
"step_size": 0.01,
"perturb_steps": 100,
"search_radius": 0.1,
"verbose": False,
},
GRAPHITEWhiteboxPyTorch: {
"iterations": 100,
"step_size": 0.01,
"decay": 0.1,
"order": "Linf",
"clip_min": 0.0,
"clip_max": 1.0,
"targeted": False,
"verbose": False,
},
HopSkipJump: {
"max_iter": 1000,
"init_size": 0.05,
"learning_rate": 0.1,
"batch_size": 16,
"verbose": False,
},
BasicIterativeMethod: {
"eps": 0.3,
"eps_step": 0.01,
"targeted": False,
"nb_iter": 40,
"ord": 2,
"clip_min": 0.0,
"clip_max": 1.0,
"batch_size": 16,
"verbose": False,
},
MomentumIterativeMethod: {
"eps": 0.3,
"eps_step": 0.01,
"momentum": 1.0,
"decay_factor": 1.0,
"targeted": False,
"nb_iter": 40,
"ord": 2,
"clip_min": 0.0,
"clip_max": 1.0,
"batch_size": 16,
"verbose": False,
},
NewtonFool: {
"max_candidates": 30,
"epsilon_search": 0.1,
"verbose": False,
},
OverloadPyTorch: {
"overshoot": 0.02,
"max_iter": 1000,
"targeted": False,
"learning_rate": 0.1,
"verbose": False,
},
PixelAttack: {
"epsilon": 4,
"max_iter": 100,
"p": 10,
"targets": 1,
"loss_fn": "cross_entropy",
"verbose": False,
},
ProjectedGradientDescent: {
"eps": 0.3,
"eps_step": 0.01,
"targeted": False,
"nb_iter": 40,
"ord": 2,
"clip_min": 0.0,
"clip_max": 1.0,
"batch_size": 16,
"verbose": False,
},
ProjectedGradientDescentPyTorch: {
"eps": 0.3,
"eps_step": 0.01,
"targeted": False,
"nb_iter": 40,
"ord": 2,
"clip_min": 0.0,
"clip_max": 1.0,
"batch_size": 16,
"verbose": False,
},
SaliencyMapMethod: {
"theta": 0.1,
"gamma": 0.1,
"clip_min": 0.0,
"clip_max": 1.0,
"verbose": False,
},
ShadowAttack: {
"max_queries": 10000,
"init_size": 0.05,
"theta": 0.1,
"gamma": 0.1,
"clip_min": 0.0,
"clip_max": 1.0,
"verbose": False,
},
SpatialTransformation: {
"max_rotation": 15,
"max_translation": 5,
"max_shear": 10,
"clip_min": 0.0,
"clip_max": 1.0,
"verbose": False,
},
SquareAttack: {
"nb_iter": 1000,
"eps": 0.3,
"eps_step": 0.01,
"p_reset": 0.1,
"scale": 0.1,
"targeted": False,
"max_iter_success": float("inf"),
"verbose": False,
},
UniversalPerturbation: {
"attacks": [FastGradientMethod()],
"p": 10,
"delta": 0.2,
"max_iter_uni": 10,
"max_iter_df": 50,
"batch_size": 16,
"verbose": False,
},
VirtualAdversarialMethod: {
"eps": 0.3,
"xi": 1e-6,
"num_iterations": 1,
"norm": 2,
"clip_min": 0.0,
"clip_max": 1.0,
"verbose": False,
},
Wasserstein: {
"n_epoch": 1000,
"learning_rate": 0.01,
"decay": 0.1,
"clip_value": 0.01,
"targeted": False,
"k": 1,
"verbose": False,
},
ZooAttack: {
"max_iter": 10000,
"batch_size": 16,
"verbose": False,
"k": 1,
"delta": 0.01,
"learning_rate": 0.1,
"decay_rate": 0.0001,
},
SignOPTAttack: {
"max_iter": 10000,
"learning_rate": 0.1,
"b": 1,
"k": 1,
"mu": 0.1,
"delta": 0.01,
"verbose": False,
},
}
attack_class = attack
params = default_params.get(attack_class, {})
logger.info(f"Retrieved parameters for {attack_class.__name__}.")
return params
except Exception as e:
logger.error(f"Error retrieving parameters for attack {attack}: {e}")
raise
def get_all_attacks() -> List[AttackType]:
"""
Retrieve all attack classes to be tested.
Returns:
List[AttackType]: List of attack classes.
"""
try:
attacks = [
AdversarialPatch,
AdversarialPatchNumpy,
AdversarialPatchPyTorch,
AdversarialTexturePyTorch,
AutoAttack,
AutoProjectedGradientDescent,
AutoConjugateGradient,
BrendelBethgeAttack,
BoundaryAttack,
CompositeAdversarialAttackPyTorch,
CarliniL2Method,
CarliniLInfMethod,
DeepFool,
DPatch,
RobustDPatch,
ElasticNet,
FastGradientMethod,
GeoDA,
GRAPHITEWhiteboxPyTorch,
HopSkipJump,
BasicIterativeMethod,
MomentumIterativeMethod,
NewtonFool,
OverloadPyTorch,
PixelAttack,
ProjectedGradientDescent,
ProjectedGradientDescentPyTorch,
SaliencyMapMethod,
ShadowAttack,
SpatialTransformation,
SquareAttack,
UniversalPerturbation,
VirtualAdversarialMethod,
Wasserstein,
ZooAttack,
SignOPTAttack,
]
logger.info(f"Retrieved {len(attacks)} attack(s).")
return attacks
except Exception as e:
logger.error(f"Error retrieving all attacks: {e}")
raise
This module serves as a robust foundation for managing defenses and attacks within the ART framework, ensuring that adversarial robustness testing can be conducted efficiently and effectively.