### Initialize Pre-built Model Architectures Source: https://context7.com/thuyimingli/backdoorbox/llms.txt Provides examples of how to instantiate various pre-built neural network architectures available in the BackdoorBox core library, including ResNet, VGG, and UNet variants. ```python model_resnet18 = core.models.ResNet(18) model_resnet18_gtsrb = core.models.ResNet(18, num_classes=43) model_mnist = core.models.BaselineMNISTNetwork() model_ae = core.models.AutoEncoder() model_unet = core.models.UNet() model_vgg16 = vgg16() ``` -------------------------------- ### Get and Display Poisoned Datasets (Python) Source: https://github.com/thuyimingli/backdoorbox/blob/main/tests/test_refool_vis.ipynb This snippet demonstrates how to retrieve poisoned training and testing datasets using the refool library and then visualize the first 10 images from each dataset. It assumes the existence of a `show_img` function for displaying images. ```python poisoned_train_dataset, poisoned_test_dataset = refool.get_poisoned_dataset() print("============train_images============") for i in range(10): show_img(poisoned_train_dataset[i][0]) print("============test_images============") for i in range(10): show_img(poisoned_test_dataset[i][0]) ``` -------------------------------- ### Environment Configuration Script Source: https://github.com/thuyimingli/backdoorbox/blob/main/README.md This script configures the necessary environment for the BackdoorBox project by cloning the repository, creating a conda environment, activating it, and installing dependencies. ```bash git clone https://github.com/THUYimingLi/BackdoorBox.git cd BackdoorBox conda create -n backdoorbox python=3.8 conda activate backdoorbox pip install -r requirements.txt ``` -------------------------------- ### Configure ShrinkPad Defense Parameters Source: https://github.com/thuyimingli/backdoorbox/blob/main/README.md Sets up the ShrinkPad preprocessing defense parameters and evaluation settings to assess model robustness against backdoor attacks. ```python shrinkpad = core.ShrinkPad(size_map=32, pad=4) schedule = {'test_model': 'path/to/poisoned_model.pth', 'batch_size': 64, 'metric': 'ASR_NoTarget'} ``` -------------------------------- ### ShrinkPad Defense Implementation Source: https://context7.com/thuyimingli/backdoorbox/llms.txt Demonstrates the ShrinkPad defense mechanism, which preprocesses images by shrinking and padding them to disrupt backdoor triggers. This involves loading a poisoned model and dataset, creating a BadNets attack instance to generate a poisoned test set, and then initializing the ShrinkPad defense. ```python import torch import torch.nn as nn import torchvision from torchvision.transforms import Compose, ToTensor, RandomHorizontalFlip import core from core.utils import any2tensor # Load model and datasets model = core.models.ResNet(18) model.load_state_dict(torch.load('path/to/poisoned_model.pth')) transform_test = Compose([ToTensor()]) testset = torchvision.datasets.CIFAR10('./data', train=False, transform=transform_test, download=True) # Create attack to get poisoned test dataset pattern = torch.zeros((32, 32), dtype=torch.uint8) pattern[-3:, -3:] = 255 weight = torch.zeros((32, 32), dtype=torch.float32) weight[-3:, -3:] = 1.0 attack = core.BadNets( train_dataset=testset, test_dataset=testset, model=model, loss=nn.CrossEntropyLoss(), y_target=1, poisoned_rate=0.05, pattern=pattern, weight=weight ) _, poisoned_testset = attack.get_poisoned_dataset() # Create ShrinkPad defense defense = core.ShrinkPad( size_map=32, # Original image size pad=4, # Padding size seed=666, deterministic=True ) ``` -------------------------------- ### Execute ShrinkPad Defense Source: https://github.com/thuyimingli/backdoorbox/blob/main/README.md Runs the ShrinkPad defense script via command line to mitigate corner-positioned triggers in CIFAR-10 models. ```bash python Defense_ShrinkPad.py ``` -------------------------------- ### Evaluate Model Performance with BackdoorBox Source: https://context7.com/thuyimingli/backdoorbox/llms.txt Demonstrates how to evaluate a model's benign accuracy and attack success rate using the BackdoorBox testing utility. It requires a configured schedule dictionary and a target dataset. ```python schedule_ba = {'device': 'GPU', 'test_model': 'path/to/poisoned_model.pth', 'metric': 'BA', 'save_dir': 'experiments', 'experiment_name': 'ShrinkPad_defense_BA'} defense.test(model, testset, schedule_ba) schedule_asr = {'device': 'GPU', 'test_model': 'path/to/poisoned_model.pth', 'metric': 'ASR_NoTarget', 'y_target': 1, 'save_dir': 'experiments', 'experiment_name': 'ShrinkPad_defense_ASR'} defense.test(model, poisoned_testset, schedule_asr) ``` -------------------------------- ### POST /train Source: https://context7.com/thuyimingli/backdoorbox/llms.txt Configures and executes the training process for either a benign or a poisoned model using a provided schedule dictionary. ```APIDOC ## POST /train ### Description Initiates the training process for a model based on a specified configuration schedule, allowing toggling between benign and poisoned training modes. ### Method POST ### Endpoint /train ### Parameters #### Request Body - **schedule** (object) - Required - A dictionary containing training parameters such as batch_size, lr, epochs, and benign_training boolean flag. ### Request Example { "device": "GPU", "benign_training": false, "batch_size": 128, "lr": 0.1, "epochs": 200, "experiment_name": "train_poisoned_CIFAR10" } ### Response #### Success Response (200) - **status** (string) - Training completion status - **model_path** (string) - Path to the saved model file ``` -------------------------------- ### Execute Pruning Defense Source: https://context7.com/thuyimingli/backdoorbox/llms.txt Demonstrates how to apply a pruning defense to a model using a subset of training data. It includes configuration for pruning schedules and methods for evaluating benign accuracy and attack success rate. ```python p = 0.2 num_subset = int(len(trainset) * p) subset, _ = random_split(trainset, [num_subset, len(trainset) - num_subset]) pruning = core.Pruning(train_dataset=subset, test_dataset=testset, model=model, layer='layer2', prune_rate=0.2, seed=666, deterministic=True) prune_schedule = {'device': 'GPU', 'CUDA_VISIBLE_DEVICES': '0', 'GPU_num': 1, 'batch_size': 128, 'num_workers': 4} pruning.repair(prune_schedule) pruning.test(test_schedule_ba) pruning.test(test_schedule_asr) ``` -------------------------------- ### Python Training Schedule Configuration Source: https://context7.com/thuyimingli/backdoorbox/llms.txt Defines the complete training schedule with various options including device configuration, training mode, data loading, optimizer settings, training duration, logging, and saving parameters. This dictionary is used to control the training process of models. ```python training_schedule = { # Device configuration 'device': 'GPU', 'CUDA_VISIBLE_DEVICES': '0,1', 'CUDA_SELECTED_DEVICES': '0', 'GPU_num': 1, # Training mode 'benign_training': False, # Data loading 'batch_size': 128, 'num_workers': 4, # Optimizer settings 'lr': 0.1, 'momentum': 0.9, 'weight_decay': 5e-4, 'gamma': 0.1, 'schedule': [150, 180], # Training duration 'epochs': 200, # Warmup (optional) 'warmup_epoch': 5, # Pretrained weights (optional) 'pretrain': 'path/to/pretrained.pth', # Logging and saving 'log_iteration_interval': 100, 'test_epoch_interval': 10, 'save_epoch_interval': 10, 'save_dir': 'experiments', 'experiment_name': 'experiment_1', } ``` -------------------------------- ### Load Custom Dataset and Run BadNets Attack Source: https://context7.com/thuyimingli/backdoorbox/llms.txt Shows how to use torchvision's DatasetFolder to load custom datasets like GTSRB and configure a BadNets attack. It defines trigger patterns and training schedules for model poisoning. ```python trainset = DatasetFolder(root=osp.join(datasets_root, 'GTSRB', 'train'), loader=cv2.imread, extensions=('png',), transform=transform_train) badnets = core.BadNets(train_dataset=trainset, test_dataset=testset, model=core.models.ResNet(18, num_classes=43), loss=nn.CrossEntropyLoss(), y_target=1, poisoned_rate=0.05, pattern=pattern, weight=weight) badnets.train(schedule) badnets.test(schedule) ``` -------------------------------- ### Dataset Loading and Refool Attack on CIFAR10 Source: https://github.com/thuyimingli/backdoorbox/blob/main/tests/test_refool_vis.ipynb Sets up transformations and loads the CIFAR10 dataset. It then initializes and applies the Refool attack to create poisoned CIFAR10 datasets, visualizing the first 10 training and testing images. ```python transform_train = Compose([ RandomHorizontalFlip(), ToTensor(), ]) transform_test = Compose([ ToTensor(), ]) trainset = CIFAR10( root='/data/ganguanhao/datasets', transform=transform_train, target_transform=None, train=True, download=True) testset = CIFAR10( root='/data/ganguanhao/datasets', transform=transform_test, target_transform=None, train=False, download=True) refool= core.Refool( train_dataset=trainset, test_dataset=testset, model=core.models.ResNet(18), loss=nn.CrossEntropyLoss(), y_target=1, poisoned_rate=0.05, poisoned_transform_train_index=0, poisoned_transform_test_index=0, poisoned_target_transform_index=0, schedule=None, seed=global_seed, deterministic=deterministic, reflection_candidates = reflection_images, ) poisoned_train_dataset, poisoned_test_dataset = refool.get_poisoned_dataset() print("============train_images============") for i in range(10): show_img(poisoned_train_dataset[i][0]) print("============test_images============") for i in range(10): show_img(poisoned_test_dataset[i][0]) ``` -------------------------------- ### POST /attack/wanet Source: https://context7.com/thuyimingli/backdoorbox/llms.txt Initializes and executes a WaNet backdoor attack using warping grids to create imperceptible triggers. ```APIDOC ## POST /attack/wanet ### Description Configures the WaNet attack instance with identity and noise grids to perform warping-based backdoor injection. ### Method POST ### Endpoint /attack/wanet ### Parameters #### Request Body - **identity_grid** (tensor) - Required - Pre-generated identity warping grid. - **noise_grid** (tensor) - Required - Pre-generated noise warping grid. - **poisoned_rate** (float) - Required - Percentage of the dataset to poison. ### Request Example { "y_target": 0, "poisoned_rate": 0.1, "seed": 666 } ### Response #### Success Response (200) - **poisoned_dataset** (object) - The resulting dataset containing both clean and poisoned samples. ``` -------------------------------- ### Import Libraries for Data Visualization and Attack Source: https://github.com/thuyimingli/backdoorbox/blob/main/tests/test_refool_vis.ipynb Imports necessary libraries for handling datasets, image manipulation, neural networks, and visualization. Includes PyTorch, torchvision, OpenCV, and Matplotlib. ```python ''' This is the test code for visualizing poisoned training on CIFAR10, MNIST, using dataset class of torchvision.datasets.DatasetFolder torchvision.datasets.CIFAR10 torchvision.datasets.MNIST. Attack method is Refool. ''' import os import cv2 import torch import torch.nn as nn from torch.utils.data import Dataset, dataloader import torchvision from torchvision import transforms from torchvision.datasets import CIFAR10, MNIST, DatasetFolder from torchvision.transforms import Compose, ToTensor, PILToTensor, RandomHorizontalFlip from torch.utils.data import DataLoader import core import matplotlib.pyplot as plt ``` -------------------------------- ### Implement BadNets Backdoor Attack in Python Source: https://context7.com/thuyimingli/backdoorbox/llms.txt This snippet demonstrates how to implement the BadNets backdoor attack using the BackdoorBox Python toolbox. It includes loading datasets (CIFAR-10), defining a visible trigger pattern, creating a BadNets attack instance with specified parameters like target class and poisoning rate, configuring a training schedule, training the backdoored model, and evaluating its performance. Dependencies include PyTorch, Torchvision, and the core BackdoorBox library. ```python import torch import torch.nn as nn import torchvision from torchvision.transforms import Compose, ToTensor, RandomHorizontalFlip import core # Load CIFAR-10 dataset transform_train = Compose([RandomHorizontalFlip(), ToTensor()]) trainset = torchvision.datasets.CIFAR10('./data', train=True, transform=transform_train, download=True) transform_test = Compose([ToTensor()]) testset = torchvision.datasets.CIFAR10('./data', train=False, transform=transform_test, download=True) # Define trigger pattern: 3x3 white square at bottom-right corner pattern = torch.zeros((32, 32), dtype=torch.uint8) pattern[-3:, -3:] = 255 weight = torch.zeros((32, 32), dtype=torch.float32) weight[-3:, -3:] = 1.0 # Create BadNets attack instance badnets = core.BadNets( train_dataset=trainset, test_dataset=testset, model=core.models.ResNet(18), loss=nn.CrossEntropyLoss(), y_target=1, # Target class for poisoned samples poisoned_rate=0.05, # 5% of training data is poisoned pattern=pattern, weight=weight, seed=666, deterministic=True ) # Training schedule configuration schedule = { 'device': 'GPU', 'CUDA_SELECTED_DEVICES': '0', 'benign_training': False, # Set True for benign training, False for attack 'batch_size': 128, 'num_workers': 4, 'lr': 0.1, 'momentum': 0.9, 'weight_decay': 5e-4, 'gamma': 0.1, 'schedule': [150, 180], # Epochs to decay learning rate 'epochs': 200, 'log_iteration_interval': 100, 'test_epoch_interval': 10, 'save_epoch_interval': 10, 'save_dir': 'experiments', 'experiment_name': 'ResNet-18_CIFAR-10_BadNets' } # Train the backdoored model badnets.train(schedule) # Get poisoned datasets for evaluation poisoned_train_dataset, poisoned_test_dataset = badnets.get_poisoned_dataset() # Test the model badnets.test(schedule) # Get the trained model infected_model = badnets.get_model() ``` -------------------------------- ### Dataset Loading and Refool Attack on MNIST Source: https://github.com/thuyimingli/backdoorbox/blob/main/tests/test_refool_vis.ipynb Configures transformations and loads the MNIST dataset. It initializes a DataLoader for the training set and sets up the Refool attack with a specific model for MNIST, preparing for data poisoning. ```python transform_train = Compose([ RandomHorizontalFlip(), ToTensor(), ]) transform_test = Compose([ ToTensor(), ]) trainset = MNIST( root='/data/ganguanhao/datasets', transform=transform_train, target_transform=None, train=True, download=True) testset = MNIST( root='/data/ganguanhao/datasets', transform=transform_test, target_transform=None, train=False, download=True) loader = DataLoader(trainset,) refool= core.Refool( train_dataset=trainset, test_dataset=testset, model=core.models.BaselineMNISTNetwork(), loss=nn.CrossEntropyLoss(), y_target=1, poisoned_rate=0.05, poisoned_transform_train_index=0, poisoned_transform_test_index=0, poisoned_target_transform_index=0, schedule=None, seed=global_seed, deterministic=deterministic, reflection_candidates = reflection_images, ) ``` -------------------------------- ### POST /defense/shrinkpad Source: https://context7.com/thuyimingli/backdoorbox/llms.txt Applies the ShrinkPad defense mechanism to mitigate backdoor triggers by resizing and random padding. ```APIDOC ## POST /defense/shrinkpad ### Description Wraps the input model or dataset with the ShrinkPad defense to disrupt corner-positioned backdoor triggers. ### Method POST ### Endpoint /defense/shrinkpad ### Parameters #### Request Body - **size_map** (int) - Required - The original image dimension. - **pad** (int) - Required - The padding size to apply. ### Request Example { "size_map": 32, "pad": 4 } ### Response #### Success Response (200) - **defense_applied** (boolean) - Confirmation that the defense wrapper is active. ``` -------------------------------- ### WaNet Attack Implementation Source: https://context7.com/thuyimingli/backdoorbox/llms.txt Implements the WaNet backdoor attack, which uses imperceptible warping-based triggers. This involves generating custom warping grids, setting up datasets, initializing the WaNet attack instance with specific parameters, and training the backdoored model. ```python import torch import torch.nn as nn import torchvision from torchvision.transforms import Compose, ToTensor, RandomHorizontalFlip import core # Generate identity grid and noise grid for warping def gen_grid(height, k): """Generate warping grids for WaNet attack.""" ins = torch.rand(1, 2, k, k) * 2 - 1 ins = ins / torch.mean(torch.abs(ins)) noise_grid = nn.functional.interpolate(ins, size=height, mode="bicubic", align_corners=True) noise_grid = noise_grid.permute(0, 2, 3, 1) array1d = torch.linspace(-1, 1, steps=height) x, y = torch.meshgrid(array1d, array1d) identity_grid = torch.stack((y, x), 2)[None, ...] return identity_grid, noise_grid # Load dataset transform_train = Compose([ToTensor(), RandomHorizontalFlip()]) trainset = torchvision.datasets.CIFAR10('data', train=True, transform=transform_train, download=True) transform_test = Compose([ToTensor()]) testset = torchvision.datasets.CIFAR10('data', train=False, transform=transform_test, download=True) # Generate warping grids identity_grid, noise_grid = gen_grid(32, 4) # Create WaNet attack instance wanet = core.WaNet( train_dataset=trainset, test_dataset=testset, model=core.models.ResNet(18), loss=nn.CrossEntropyLoss(), y_target=0, poisoned_rate=0.1, identity_grid=identity_grid, noise_grid=noise_grid, noise=False, # Set True to add noise mode during training seed=666, deterministic=True ) # Training schedule schedule = { 'device': 'GPU', 'CUDA_SELECTED_DEVICES': '0', 'benign_training': False, 'batch_size': 128, 'num_workers': 4, 'lr': 0.1, 'momentum': 0.9, 'weight_decay': 5e-4, 'gamma': 0.1, 'schedule': [150, 180], 'epochs': 200, 'log_iteration_interval': 100, 'test_epoch_interval': 10, 'save_epoch_interval': 10, 'save_dir': 'experiments', 'experiment_name': 'ResNet-18_CIFAR-10_WaNet' } wanet.train(schedule) poisoned_train_dataset, poisoned_test_dataset = wanet.get_poisoned_dataset() # Save grids for later use in defense testing torch.save(identity_grid, 'wanet_identity_grid.pth') torch.save(noise_grid, 'wanet_noise_grid.pth') ``` -------------------------------- ### Configure Model and Training Hyperparameters Source: https://github.com/thuyimingli/backdoorbox/blob/main/README.md Initializes a ResNet-18 model architecture and defines training hyperparameters including poison rate and target class for backdoor injection. ```python model = core.models.ResNet(18, num_classes=50) poisoned_rate = 0.1 y_target = 1 schedule = {'lr': 0.1, 'batch_size': 128, 'epochs': 100} ``` -------------------------------- ### Python Testing Schedule Configuration Source: https://context7.com/thuyimingli/backdoorbox/llms.txt Defines the testing schedule, including device configuration, model path, data loading parameters, evaluation metrics, target class for specific metrics, and directories for saving results. This dictionary controls the evaluation of trained models. ```python testing_schedule = { 'device': 'GPU', 'CUDA_VISIBLE_DEVICES': '0', 'GPU_num': 1, 'test_model': 'path/to/model.pth', 'batch_size': 128, 'num_workers': 4, 'metric': 'ASR_NoTarget', 'y_target': 1, 'save_dir': 'experiments', 'experiment_name': 'test_result', } ``` -------------------------------- ### Configure Pruning Defense and Poisoned Evaluation Source: https://context7.com/thuyimingli/backdoorbox/llms.txt Sets up a pruning defense environment and generates a poisoned test set for evaluating the effectiveness of the defense against backdoor attacks. ```python attack = core.BadNets(train_dataset=trainset, test_dataset=testset, model=deepcopy(model), loss=nn.CrossEntropyLoss(), y_target=1, poisoned_rate=0.05, pattern=pattern, weight=weight) _, poisoned_testset = attack.get_poisoned_dataset() ``` -------------------------------- ### Dataset Loading and Refool Attack on Custom Folder Data Source: https://github.com/thuyimingli/backdoorbox/blob/main/tests/test_refool_vis.ipynb Configures image transformations and loads datasets from a custom folder structure using `DatasetFolder`. It then initializes and applies the Refool attack to generate poisoned datasets, visualizing the results. ```python transform_train = Compose([ transforms.ToPILImage(), # transforms.Resize((32,32)), RandomHorizontalFlip(), ToTensor(), ]) transform_test = Compose([ transforms.ToPILImage(), # transforms.Resize((32,32)), ToTensor(), ]) trainset = DatasetFolder( root='/data/ganguanhao/datasets/cifar10-folder/trainset', loader=cv2.imread, extensions=('png',), transform=transform_train, target_transform=None, is_valid_file=None) testset = DatasetFolder( root='/data/ganguanhao/datasets/cifar10-folder/testset', loader=cv2.imread, extensions=('png',), transform=transform_train, target_transform=None, is_valid_file=None) refool= core.Refool( train_dataset=trainset, test_dataset=testset, model=core.models.ResNet(18), loss=nn.CrossEntropyLoss(), y_target=1, poisoned_rate=0.05, poisoned_transform_train_index=0, poisoned_transform_test_index=0, poisoned_target_transform_index=0, schedule=None, seed=global_seed, deterministic=deterministic, reflection_candidates = reflection_images, ) poisoned_train_dataset, poisoned_test_dataset = refool.get_poisoned_dataset() print("============train_images============") for i in range(10): show_img(poisoned_train_dataset[i][0]) print("============test_images============") for i in range(10): show_img(poisoned_test_dataset[i][0]) ``` -------------------------------- ### Implement Neural Attention Distillation (NAD) Defense Source: https://context7.com/thuyimingli/backdoorbox/llms.txt Configures and runs the NAD defense to repair backdoored models. It involves setting up a teacher-student distillation process with specific layer targets and training schedules. ```python defense = core.NAD(model=model, loss=nn.CrossEntropyLoss(), power=2.0, beta=[500, 500, 500], target_layers=['layer2', 'layer3', 'layer4'], seed=666, deterministic=True) repair_schedule = {'device': 'GPU', 'batch_size': 64, 'lr': 0.01, 'tune_epochs': 10, 'epochs': 20, 'save_dir': 'experiments/NAD-defense'} defense.repair(dataset=trainset, portion=0.05, schedule=repair_schedule) repaired_model = defense.get_model() ``` -------------------------------- ### Image Reading and Display Utilities in Python Source: https://github.com/thuyimingli/backdoorbox/blob/main/tests/test_refool_vis.ipynb Defines functions to read images using OpenCV, supporting different color formats (RGB, Grayscale), and to display images using Matplotlib. It also sets up global seeds for reproducibility. ```python global_seed = 666 deterministic = True torch.manual_seed(global_seed) reflection_data_dir = "/data/ganguanhao/datasets/VOCdevkit/VOC2012/JPEGImages/" def read_image(img_path, type=None): img = cv2.imread(img_path) if type is None: return img elif isinstance(type,str) and type.upper() == "RGB": return cv2.cvtColor(img, cv2.COLOR_BGR2RGB) elif isinstance(type,str) and type.upper() == "GRAY": return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) else: raise NotImplementedError reflection_image_path = os.listdir(reflection_data_dir) reflection_images = [read_image(os.path.join(reflection_data_dir,img_path)) for img_path in reflection_image_path[:200]] def show_img(x): img = cv2.cvtColor(x.permute(1,2,0).numpy(),cv2.COLOR_BGR2RGB) plt.imshow(img) plt.show() ``` -------------------------------- ### Blended Attack Configuration (Python) Source: https://github.com/thuyimingli/backdoorbox/blob/main/README.md Configuration for the Blended attack, which involves setting up trigger transparency and other attack-specific parameters. ```python # Trigger Settings # Blended attack with alpha=0.2 transparency trigger on ImageNet50. ``` -------------------------------- ### Implement Blended Backdoor Attack in Python Source: https://context7.com/thuyimingli/backdoorbox/llms.txt This snippet shows how to implement the Blended backdoor attack using the BackdoorBox Python toolbox. It involves loading datasets, defining an invisible trigger pattern using alpha blending, creating a Blended attack instance with parameters like target class and poisoning rate, and retrieving poisoned datasets for inspection. This attack method aims to make poisoned samples visually indistinguishable from clean ones. ```python import torch import torch.nn as nn import torchvision from torchvision.transforms import Compose, ToTensor, RandomHorizontalFlip import core # Load dataset transform_train = Compose([ToTensor(), RandomHorizontalFlip()]) trainset = torchvision.datasets.CIFAR10('data', train=True, transform=transform_train, download=True) transform_test = Compose([ToTensor()]) testset = torchvision.datasets.CIFAR10('data', train=False, transform=transform_test, download=True) # Define blended trigger: semi-transparent pattern pattern = torch.zeros((1, 32, 32), dtype=torch.uint8) pattern[0, -3:, -3:] = 255 weight = torch.zeros((1, 32, 32), dtype=torch.float32) weight[0, -3:, -3:] = 0.2 # Alpha blending factor (20% trigger visibility) # Create Blended attack instance blended = core.Blended( train_dataset=trainset, test_dataset=testset, model=core.models.ResNet(18), loss=nn.CrossEntropyLoss(), pattern=pattern, weight=weight, y_target=1, poisoned_rate=0.05, seed=666, deterministic=True ) # Get poisoned datasets to inspect poisoned_train_dataset, poisoned_test_dataset = blended.get_poisoned_dataset() ``` -------------------------------- ### Train Benign and Backdoored Models Source: https://context7.com/thuyimingli/backdoorbox/llms.txt Configures and trains both a benign model and a backdoored model using specified schedules. It involves setting training parameters like batch size, learning rate, and epochs, and then retrieving the trained models. ```python benign_schedule = { 'device': 'GPU', 'CUDA_VISIBLE_DEVICES': '0', 'GPU_num': 1, 'benign_training': True, 'batch_size': 128, 'num_workers': 4, 'lr': 0.1, 'momentum': 0.9, 'weight_decay': 5e-4, 'gamma': 0.1, 'schedule': [150, 180], 'epochs': 200, 'log_iteration_interval': 100, 'test_epoch_interval': 10, 'save_epoch_interval': 10, 'save_dir': 'experiments', 'experiment_name': 'train_benign_CIFAR10_Blended' } # Train benign model first blended.train(benign_schedule) benign_model = blended.get_model() # Reset model and train backdoored version blended.model = core.models.ResNet(18) poisoned_schedule = benign_schedule.copy() poisoned_schedule['benign_training'] = False poisoned_schedule['experiment_name'] = 'train_poisoned_CIFAR10_Blended' blended.train(poisoned_schedule) infected_model = blended.get_model() ``` -------------------------------- ### BadNets Attack Configuration (Python) Source: https://github.com/thuyimingli/backdoorbox/blob/main/README.md Configuration for the BadNets attack, specifying trigger pattern, weight, model architecture, and training hyperparameters like poisoned rate and target class. ```python # Trigger Settings pattern = torch.zeros((1, 32, 32), dtype=torch.uint8) pattern[0, -3:, -3:] = 255 weight = torch.zeros((1, 32, 32), dtype=torch.float32) weight[0, -3:, -3:] = 1.0 # Model Architecture model = core.models.ResNet(18) # Change to other supported models # Hyperparameters poisoned_rate = 0.05 # 5% poisoned samples y_target = 1 # Target class # Training schedule schedule = { 'lr': 0.1, 'batch_size': 128, 'epochs': 200, # ... other parameters } ``` -------------------------------- ### Define Semi-transparent 3x3 Trigger Source: https://github.com/thuyimingli/backdoorbox/blob/main/README.md Creates a 3x3 pixel trigger pattern with alpha blending using PyTorch tensors. This is used to define the visual backdoor trigger applied to input images. ```python import torch pattern = torch.zeros((3, 224, 224), dtype=torch.uint8) pattern[:, -3:, -3:] = 255 weight = torch.zeros((3, 224, 224), dtype=torch.float32) weight[:, -3:, -3:] = 0.2 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.