-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3N_attack.py
More file actions
2230 lines (1908 loc) · 86.2 KB
/
Copy path3N_attack.py
File metadata and controls
2230 lines (1908 loc) · 86.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import torch
import torch.nn as nn
import torch.nn.functional as F
import pandas as pad
import seaborn as sns
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models
import math
import os
import matplotlib.pyplot as plt
import copy
from torch.utils.data import DataLoader, Subset
from copy import deepcopy
from collections import defaultdict
import argparse
import numpy as np
from typing import List, Dict, Tuple
from itertools import product
import pandas as pd
from baseline_MNIST_network import MNIST_CNN
import random
def set_seed(seed):
"""
Set random seeds for reproducibility across all libraries.
Args:
seed: Integer seed value
"""
print(f"Setting random seed to: {seed}")
# Python's random module
random.seed(seed)
# NumPy
np.random.seed(seed)
# PyTorch CPU
torch.manual_seed(seed)
# PyTorch GPU
if torch.cuda.is_available():
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed) # for multi-GPU
# Make CUDA operations deterministic
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
# Make sure PyTorch operations are deterministic
torch.use_deterministic_algorithms(True, warn_only=True)
# Set environment variables for additional determinism
os.environ['PYTHONHASHSEED'] = str(seed)
os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8'
def seed_worker(worker_id):
"""
Worker init function for DataLoader to ensure reproducibility.
"""
worker_seed = torch.initial_seed() % 2**32
np.random.seed(worker_seed)
random.seed(worker_seed)
def get_single_class_loader(loader, target_class, max_samples=None, device='cuda'):
"""
Extract samples from a single class from a dataloader.
Args:
loader: Original dataloader
target_class: Class label to filter for
max_samples: Maximum number of samples to collect (None = all)
device: Device to use
Returns:
Single batch containing only target_class samples
"""
images = []
labels = []
for x, y in loader:
# Get indices where y == target_class
mask = (y == target_class)
if mask.any():
images.append(x[mask])
labels.append(y[mask])
# Check if we have enough samples
if max_samples and sum(len(img) for img in images) >= max_samples:
break
if not images:
raise ValueError(f"No samples found for class {target_class}")
# Concatenate all collected samples
all_images = torch.cat(images, dim=0)
all_labels = torch.cat(labels, dim=0)
# Limit to max_samples if specified
if max_samples:
all_images = all_images[:max_samples]
all_labels = all_labels[:max_samples]
return all_images, all_labels
def get_imagenet(batch_size=128, subset=None, imagenet_path='../imagenet/', seed=42):
"""Load ImageNet dataset using the exact same approach as the working script"""
# Use the exact same transform as the working script
transform_test = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
])
# Use the exact same dataset loading approach
test_data = datasets.ImageNet(imagenet_path, split='val', transform=transform_test)
print(f'Test data length: {len(test_data)}')
g = torch.Generator()
g.manual_seed(seed)
# Use the exact same subset approach
if subset:
test_data, _ = torch.utils.data.random_split(
test_data,
[subset, len(test_data) - subset],
generator=g
)
# Create dummy train data (since we don't use it anyway)
train_data = test_data
# Use the exact same DataLoader settings
train_loader = DataLoader(
train_data,
batch_size=batch_size,
shuffle=True,
num_workers=4,
pin_memory=True
)
test_loader = DataLoader(
test_data,
batch_size=batch_size,
shuffle=False,
num_workers=8,
pin_memory=True,
persistent_workers=True if batch_size > 64 else False,
prefetch_factor=2,
drop_last=False
)
return train_loader, test_loader
def get_data(args):
import torchvision.transforms as transforms
import torchvision.datasets as dsets
from torch.utils.data import Subset
import os
# Dataset-specific configurations
dataset_configs = {
"mnist": {
"num_classes": 10,
"train_transform": transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
]),
"test_transform": transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
},
"cifar10": {
"num_classes": 10,
"train_transform": transforms.Compose([
# Spatial augmentations
transforms.RandomCrop(32, padding=4, padding_mode='reflect'),
transforms.RandomHorizontalFlip(p=0.5),
transforms.RandomRotation(15),
transforms.RandomAffine(degrees=0, translate=(0.1, 0.1)),
# Color augmentations (more aggressive)
transforms.ColorJitter(
brightness=0.4,
contrast=0.4,
saturation=0.4,
hue=0.1
),
# Convert to tensor and normalize
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
# Cutout/Random Erasing
transforms.RandomErasing(
p=0.25,
scale=(0.02, 0.33),
ratio=(0.3, 3.3),
value=0,
inplace=False
),
]),
"test_transform": transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
])
},
"gtsrb": {
"num_classes": 43,
"train_transform": transforms.Compose([
transforms.Resize(256),
transforms.RandomCrop(224, padding=4),
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1),
transforms.RandomRotation(15),
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
]),
"test_transform": transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
])
},
# Add ImageNet configuration
"imagenet": {
"num_classes": 1000,
"train_transform": transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1),
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
]),
"test_transform": transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
])
},
}
if args.dataset not in dataset_configs:
raise KeyError(f"Dataset '{args.dataset}' not supported")
config = dataset_configs[args.dataset]
num_classes = config["num_classes"]
# Create generator for reproducibility
g = torch.Generator()
g.manual_seed(args.seed)
# Load datasets based on type
if args.dataset == "mnist":
train_data = dsets.MNIST(
root=getattr(args, 'dataset_dir', './data'),
train=True,
transform=config["train_transform"],
download=True
)
test_data = dsets.MNIST(
root=getattr(args, 'dataset_dir', './data'),
train=False,
transform=config["test_transform"],
download=True
)
args.input_size = 28
elif args.dataset == "cifar10":
train_data = dsets.CIFAR10(
root=getattr(args, 'dataset_dir', './data'),
train=True,
download=True,
transform=config["train_transform"]
)
test_data = dsets.CIFAR10(
root=getattr(args, 'dataset_dir', './data'),
train=False,
download=True,
transform=config["test_transform"]
)
args.input_size = 32
elif args.dataset == "gtsrb":
train_data = dsets.GTSRB(
root=getattr(args, 'dataset_dir', './data'),
split='train',
download=True,
transform=config["train_transform"]
)
test_data = dsets.GTSRB(
root=getattr(args, 'dataset_dir', './data'),
split='test',
download=True,
transform=config["test_transform"]
)
args.input_size = 32
elif args.dataset == "imagenet":
# Use custom ImageNet loading function
imagenet_path = getattr(args, 'imagenet_path', '../imagenet/')
# Don't use the config transforms - use the working approach directly
train_loader, test_loader = get_imagenet(
batch_size=args.batch_size,
subset=args.subset,
imagenet_path=imagenet_path,
seed=args.seed
)
args.input_size = 224
return train_loader, test_loader, 1000 # Return directly
# Apply subset if specified
if hasattr(args, 'subset') and args.subset:
# Use random_split with generator for reproducibility
train_data, _ = torch.utils.data.random_split(
train_data,
[args.subset, len(train_data) - args.subset],
generator=g
)
test_data, _ = torch.utils.data.random_split(
test_data,
[args.subset, len(test_data) - args.subset],
generator=g
)
# Create data loaders with worker seeding
train_loader = torch.utils.data.DataLoader(
dataset=train_data,
batch_size=args.batch_size,
shuffle=True,
num_workers=4,
pin_memory=True,
worker_init_fn=seed_worker,
generator=g # Use generator for shuffling
)
test_loader = torch.utils.data.DataLoader(
dataset=test_data,
batch_size=args.batch_size,
shuffle=False, # Don't shuffle test
num_workers=4,
pin_memory=True,
worker_init_fn=seed_worker,
generator=g
)
return train_loader, test_loader, num_classes
def get_gtsrb(batch_size=128, subset=None):
"""Load GTSRB dataset with its own normalization"""
train_transform = transforms.Compose([
transforms.Resize((32, 32)),
transforms.RandomRotation(15),
transforms.RandomAffine(degrees=0, translate=(0.1, 0.1)),
transforms.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3, hue=0.1),
transforms.RandomPerspective(distortion_scale=0.1, p=0.3),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
test_transform = transforms.Compose([
transforms.Resize((32, 32)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
train = datasets.GTSRB(root='./data', split='train', download=True, transform=train_transform)
test = datasets.GTSRB(root='./data', split='test', download=True, transform=test_transform)
if subset:
idx = list(range(subset))
test = Subset(test, idx)
return DataLoader(train, batch_size=batch_size, shuffle=True, num_workers=4), \
DataLoader(test, batch_size=batch_size, shuffle=False, num_workers=4)
def create_detection_candidates(injection_candidates, msb_candidates, ensure_injection_included=True):
"""
Combine injection candidates with MSB candidates for detection.
Args:
injection_candidates: Dict[str, List[int]] - neurons that were actually injected
msb_candidates: Dict[str, List[int]] - neurons identified by MSB analysis
ensure_injection_included: bool - if True, always include injected neurons
"""
combined_candidates = {}
for layer in injection_candidates.keys():
# Start with MSB candidates for this layer
candidates_set = set(msb_candidates.get(layer, []))
# Add injected neurons to ensure they're monitored
if ensure_injection_included:
candidates_set.update(injection_candidates[layer])
# Convert back to sorted list
combined_candidates[layer] = sorted(list(candidates_set))
return combined_candidates
def collect_msb_stats_reduced(acts_clean: Dict[str, List[torch.Tensor]],
acts_trig: Dict[str, List[torch.Tensor]],
layers: List[str],
top_k: int = 5,
exp_bits: int = 4): # Use only top 4 bits of exponent
"""
Use only the most significant bits of the exponent field.
exp_bits: number of MSBs to use from the 8-bit exponent (1-8)
"""
msb_stats = {}
for layer in layers:
clean_t = torch.cat(acts_clean[layer], dim=0).mean(dim=(2,3)).cpu().numpy().astype(np.float32)
trig_t = torch.cat(acts_trig[layer], dim=0).mean(dim=(2,3)).cpu().numpy().astype(np.float32)
# reinterpret the bits as uint32
clean_u = clean_t.view(np.uint32)
trig_u = trig_t.view(np.uint32)
# Extract only the top exp_bits of the exponent
shift_amount = 31 - exp_bits # Shift to get top bits
mask = ((1 << exp_bits) - 1) << shift_amount
clean_exp = (clean_u & mask) >> shift_amount
trig_exp = (trig_u & mask) >> shift_amount
# Rest of the function remains the same...
mean_e_clean = clean_exp.mean(axis=0)
mean_e_trig = trig_exp.mean(axis=0)
delta_e = mean_e_trig - mean_e_clean
top_idx = np.argsort(-np.abs(delta_e))[:top_k]
msb_stats[layer] = {
'mean_e_clean': mean_e_clean,
'mean_e_trig': mean_e_trig,
'delta_e': delta_e,
'top_filters': top_idx
}
return msb_stats
def collect_msb_stats_adaptive(acts_clean: Dict[str, List[torch.Tensor]],
acts_trig: Dict[str, List[torch.Tensor]],
layers: List[str],
top_k: int = 5):
"""
Adaptively choose the number of exponent bits based on activation range.
"""
msb_stats = {}
for layer in layers:
clean_t = torch.cat(acts_clean[layer], dim=0).mean(dim=(2,3)).cpu().numpy().astype(np.float32)
trig_t = torch.cat(acts_trig[layer], dim=0).mean(dim=(2,3)).cpu().numpy().astype(np.float32)
# Determine optimal bit count based on activation range
all_vals = np.concatenate([clean_t.ravel(), trig_t.ravel()])
val_range = np.log2(np.max(np.abs(all_vals)) / np.min(np.abs(all_vals[all_vals != 0])))
# Use fewer bits if the range is small
if val_range < 4:
exp_bits = 3
elif val_range < 8:
exp_bits = 4
else:
exp_bits = 6
print(f"Layer {layer}: Using {exp_bits} exponent bits (range: {val_range:.1f})")
# Apply the reduced bit extraction
clean_u = clean_t.view(np.uint32)
trig_u = trig_t.view(np.uint32)
shift_amount = 31 - exp_bits
mask = ((1 << exp_bits) - 1) << shift_amount
clean_exp = (clean_u & mask) >> shift_amount
trig_exp = (trig_u & mask) >> shift_amount
# Continue with analysis...
def collect_msb_stats_quantized(acts_clean: Dict[str, List[torch.Tensor]],
acts_trig: Dict[str, List[torch.Tensor]],
layers: List[str],
top_k: int = 5,
num_bins: int = 8): # Quantize to 8 bins instead of 256
"""
Quantize the full exponent into fewer bins.
"""
msb_stats = {}
for layer in layers:
clean_t = torch.cat(acts_clean[layer], dim=0).mean(dim=(2,3)).cpu().numpy().astype(np.float32)
trig_t = torch.cat(acts_trig[layer], dim=0).mean(dim=(2,3)).cpu().numpy().astype(np.float32)
clean_u = clean_t.view(np.uint32)
trig_u = trig_t.view(np.uint32)
# Extract full exponent first
clean_exp_full = (clean_u >> 23) & 0xFF
trig_exp_full = (trig_u >> 23) & 0xFF
# Quantize to fewer bins
bin_size = 256 // num_bins
clean_exp = clean_exp_full // bin_size
trig_exp = trig_exp_full // bin_size
# Continue with analysis...
def msb_trigger_detector_reduced(model, x, layers, candidates, device,
apply_trigger: bool = True, exp_bits: int = 4):
"""
Modified detector using fewer exponent bits.
"""
model.eval()
acts = { (L,fi): [] for L in layers for fi in candidates[L] }
handles = []
def trigger_fn(x):
x = x.clone()
_,C,H,W = x.shape
if C == 1: # MNIST case (grayscale)
mnist_mean = 0.1307
mnist_std = 0.3081
white_val = (1.0 - mnist_mean) / mnist_std
x[:, :, H-pattern_size:H, W-pattern_size:W] = white_val
else: # RGB case
x[:, :, H-pattern_size:H, W-pattern_size:W] = white_norm
return x
def make_hook(L, idxs):
def hook(_, __, out):
for fi in idxs:
v = out[:, fi].mean(dim=(1,2)).cpu().numpy()
acts[(L,fi)].append(v[0])
return hook
# Register hooks and run passes (same as before)...
# ... (hook registration code) ...
# Count flips using reduced bits
flips = 0
shift_amount = 31 - exp_bits
mask = ((1 << exp_bits) - 1) << shift_amount
for (L,fi), vals in acts.items():
clean_val, second_val = vals
# Extract reduced exponent bits
clean_bits = np.frombuffer(np.float32(clean_val).tobytes(), dtype=np.uint32)[0]
second_bits = np.frombuffer(np.float32(second_val).tobytes(), dtype=np.uint32)[0]
e1 = (clean_bits & mask) >> shift_amount
e2 = (second_bits & mask) >> shift_amount
if e1 != e2:
flips += 1
return flips
def exponent_bit_ablation(model_fn, train_loader, test_loader, device, layers_to_patch):
"""
Ablation study to find optimal number of exponent bits.
"""
bit_counts = [2, 3, 4, 5, 6, 7, 8] # Different numbers of exponent bits
results = []
for exp_bits in bit_counts:
print(f"\n--- Testing with {exp_bits} exponent bits ---")
# Your existing injection code...
model = model_fn(device)
model, injection_candidates = inject_backdoor_on_layers(model, test_loader, device, layers_to_patch)
# Collect activations
acts_clean, acts_trig = collect_activations(model, test_loader, trigger_fn, device, layers_to_patch)
# Use reduced bits
msb_stats = collect_msb_stats_reduced(acts_clean, acts_trig, layers_to_patch, exp_bits=exp_bits)
# Evaluate detection performance
# ... (evaluation code) ...
results.append({
'exp_bits': exp_bits,
'tpr': tpr,
'fpr': fpr,
'f1': f1_score
})
return pd.DataFrame(results)
def load_resnet18(device, num_classes=10, ckpt_path=None):
"""Load ResNet-18 model with proper configuration for different datasets"""
# For smaller datasets (CIFAR-10, GTSRB), modify the first conv layer
if num_classes != 1000: # Not ImageNet
model = models.resnet18(pretrained=False)
model.fc = nn.Linear(model.fc.in_features, num_classes)
model.conv1 = nn.Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=True)
#model.maxpool = nn.Identity()
# Load the appropriate checkpoint
if num_classes == 1000: # ImageNet
model = models.resnet18(num_classes=1000)
model.conv1 = nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False)
# Default or custom path
final_path = ckpt_path if ckpt_path else "../imagenet/imagenet_models/resnet/imagenet/resnet18_imagenet_base_model.pth"
print(f"Loading model from {final_path}...")
model.load_state_dict(torch.load(final_path, weights_only=False)["model"], strict=False)
model = model.to(device)
model.eval()
return model
elif num_classes == 10: # CIFAR-10
final_path = ckpt_path if ckpt_path else './ckpt/resnet18_cifar10_base_model.pth'
print(f"Loading model from {final_path}...")
ckpt = torch.load(final_path, map_location=device, weights_only=False)
model.load_state_dict(ckpt['model'])
elif num_classes == 43: # GTSRB
final_path = ckpt_path if ckpt_path else './ckpt/resnet18_gtsrb_base_model.pth'
print(f"Loading model from {final_path}...")
ckpt = torch.load(final_path, map_location=device, weights_only=False)
model.load_state_dict(ckpt['model'])
else:
raise ValueError(f"No checkpoint available for {num_classes} classes")
model = model.to(device)
return model
def collect_activations(model, loader, trigger_fn, device, layers,
target_class=None, max_samples=None):
"""
Collect activations, accumulating enough batches to reach max_samples.
"""
model.eval()
acts_clean = {L: [] for L in layers}
acts_trig = {L: [] for L in layers}
# helper to register hooks
def get_hook(L, storage):
def hook(m, inp, out):
storage[L].append(out.detach().cpu())
return hook
handles_clean = []
handles_trig = []
# ------------------------------------------------
# 1. Prepare Data Batch (Accumulate up to max_samples)
# ------------------------------------------------
x_data = []
y_data = []
if target_class is not None:
# Use existing single class helper
x_all, y_all = get_single_class_loader(loader, target_class, max_samples, device)
x_data = [x_all] # wrap in list to treat as "batches"
else:
# General case: Loop through loader until we have enough
total_collected = 0
for x, y in loader:
x_data.append(x.to(device))
total_collected += x.size(0)
if max_samples and total_collected >= max_samples:
break
# ------------------------------------------------
# 2. Run Clean Pass
# ------------------------------------------------
for L in layers:
mod = dict(model.named_modules())[L]
handles_clean.append(mod.register_forward_hook(get_hook(L, acts_clean)))
with torch.no_grad():
current_count = 0
for x in x_data:
if max_samples and current_count >= max_samples: break
# Slice batch if needed to hit exact max_samples
remaining = max_samples - current_count if max_samples else x.size(0)
x_batch = x[:remaining].to(device)
_ = model(x_batch)
current_count += x_batch.size(0)
for h in handles_clean: h.remove()
# ------------------------------------------------
# 3. Run Triggered Pass
# ------------------------------------------------
for L in layers:
mod = dict(model.named_modules())[L]
handles_trig.append(mod.register_forward_hook(get_hook(L, acts_trig)))
with torch.no_grad():
current_count = 0
for x in x_data:
if max_samples and current_count >= max_samples: break
remaining = max_samples - current_count if max_samples else x.size(0)
x_batch = x[:remaining].to(device)
x_trig = trigger_fn(x_batch)
_ = model(x_trig)
current_count += x_batch.size(0)
for h in handles_trig: h.remove()
return acts_clean, acts_trig
def run_calibration_ablation(args, model_factory, train_loader, test_loader, trigger_fn):
results = []
# -------------------------------------------------------------------------
# 1. Setup Injection Targets (3 Neurons across 3 Layers)
# -------------------------------------------------------------------------
if args.model.startswith("resnet"):
# User requested: "only convs in the first layer"
# We pick the first 3 convs of Layer 1 to maintain "3 neurons total"
layers_to_use = ["layer2.0.conv1", "layer2.0.conv2", "layer2.1.conv1"]
elif args.model.startswith("vgg"):
layers_to_use = ["features.0", "features.3", "features.7"]
else:
layers_to_use = ["conv1", "conv2", "conv3"]
# Dictionary: 1 neuron per layer (Total 3)
dist = {l: 1 for l in layers_to_use}
print(f"--- Running Calibration Ablation (Injection varies with Set Size) ---")
print(f"Target Layers: {layers_to_use}")
# Helper to create a specific subset loader
def get_sub_loader(dataset, indices):
# We set batch_size=len(indices) so the injection function sees
# ALL these samples in the single batch it pulls.
sub = Subset(dataset, indices)
return DataLoader(sub, batch_size=len(indices), shuffle=False)
# Pre-calculate class indices for the single-class experiment
class_indices = defaultdict(list)
print("Indexing dataset by class...")
# iterate the test set once to map indices
for idx, (_, label) in enumerate(test_loader.dataset):
class_indices[label].append(idx)
# =========================================================================
# EXPERIMENT A: Calibration Set Size (Injection & Detection)
# =========================================================================
# We define a global pool of indices to draw from (0 to 500)
all_indices = list(range(len(test_loader.dataset)))
sample_sizes = [5, 10, 25, 50, 75, 100, 150, 200, 300, 400, 500]
print(f"\n--- Experiment A: Set Size Ablation ---")
for size in sample_sizes:
try:
print(f"\n[Size {size}] Starting...")
# 1. Create Restricted Loader (Used for BOTH Injection and Detection)
current_indices = all_indices[:size]
calib_loader = get_sub_loader(test_loader.dataset, current_indices)
# 2. Inject Backdoor using ONLY the restricted set
# (Simulates attacker having limited data to select neurons)
model = model_factory(args.device) # Fresh model
base_acc = evaluate(model, test_loader, args.device)
model, picks = inject_backdoor_on_layers(
model, calib_loader, args.device, # <--- Pass restricted loader
layers_to_patch=layers_to_use,
trigger_fn=trigger_fn,
per_layer_k=dist,
drop_thresh=0.5,
alpha=0.4
)
# 3. Measure Attack Success (on FULL test set)
# We want to know if the attack *worked* generally, even if selected on 5 images.
clean_acc = evaluate(model, test_loader, args.device)
acc_drop = base_acc - clean_acc
# 4. Find Monitor Neurons (using restricted set)
acts_clean, acts_trig = collect_activations(
model, calib_loader, trigger_fn, args.device, layers_to_use,
max_samples=size # redundant given loader size, but safe
)
msb_stats = collect_msb_stats(acts_clean, acts_trig, layers_to_use, top_k=5)
natural_candidates = {
layer: stats['top_filters'].tolist() for layer, stats in msb_stats.items()
}
# 5. Create Detection Set
detection_candidates = create_detection_candidates(picks, natural_candidates, True)
# 6. Evaluate Detection (on FULL test set 500)
# We test if the detector generalizes to unseen data
fp, n_clean = evaluate_msb_only_detector(model, test_loader, layers_to_use, detection_candidates, args.device, max_images=500, apply_trigger=False)
tp, n_trig = evaluate_msb_only_detector(model, test_loader, layers_to_use, detection_candidates, args.device, max_images=500, apply_trigger=True)
tpr = tp / n_trig if n_trig > 0 else 0
fpr = fp / n_clean if n_clean > 0 else 0
results.append({
"experiment": "set_size",
"param_value": size,
"tpr": tpr,
"fpr": fpr,
"clean_acc_drop": acc_drop
})
print(f"Size: {size:<4} | Drop: {acc_drop:.4f} | TPR: {tpr:.2%} | FPR: {fpr:.2%}")
except Exception as e:
print(f"Error on size {size}: {e}")
import traceback
traceback.print_exc()
# =========================================================================
# EXPERIMENT B: Single Class Calibration (Injection & Detection)
# =========================================================================
print(f"\n--- Experiment B: Single Class Ablation ---")
CLASS_CALIB_SIZE = 100
for class_idx in range(args.num_classes):
try:
print(f"\n[Class {class_idx}] Starting...")
# 1. Create Restricted Loader (Only images of class_idx)
indices = class_indices[class_idx][:CLASS_CALIB_SIZE]
if len(indices) < CLASS_CALIB_SIZE:
print(f"Warning: Class {class_idx} only has {len(indices)} samples")
calib_loader = get_sub_loader(test_loader.dataset, indices)
# 2. Inject Backdoor (Attacker only has images of Trucks)
model = model_factory(args.device)
base_acc = evaluate(model, test_loader, args.device)
model, picks = inject_backdoor_on_layers(
model, calib_loader, args.device, # <--- Pass restricted loader
layers_to_patch=layers_to_use,
trigger_fn=trigger_fn,
per_layer_k=dist,
drop_thresh=0.5,
alpha=0.4
)
clean_acc = evaluate(model, test_loader, args.device)
acc_drop = base_acc - clean_acc
# 3. Find Monitor Neurons (using restricted set)
acts_clean, acts_trig = collect_activations(
model, calib_loader, trigger_fn, args.device, layers_to_use,
max_samples=CLASS_CALIB_SIZE
)
msb_stats = collect_msb_stats(acts_clean, acts_trig, layers_to_use, top_k=5)
natural_candidates = {
layer: stats['top_filters'].tolist() for layer, stats in msb_stats.items()
}
# 4. Create Detection Set
detection_candidates = create_detection_candidates(picks, natural_candidates, True)
# 5. Evaluate (on FULL test set 500)
fp, n_clean = evaluate_msb_only_detector(model, test_loader, layers_to_use, detection_candidates, args.device, max_images=500, apply_trigger=False)
tp, n_trig = evaluate_msb_only_detector(model, test_loader, layers_to_use, detection_candidates, args.device, max_images=500, apply_trigger=True)
tpr = tp / n_trig if n_trig > 0 else 0
fpr = fp / n_clean if n_clean > 0 else 0
results.append({
"experiment": "single_class",
"param_value": class_idx,
"tpr": tpr,
"fpr": fpr,
"clean_acc_drop": acc_drop
})
print(f"Class: {class_idx:<2} | Drop: {acc_drop:.4f} | TPR: {tpr:.2%} | FPR: {fpr:.2%}")
except Exception as e:
print(f"Error on class {class_idx}: {e}")
import traceback
traceback.print_exc()
return pd.DataFrame(results)
# =========================================================================
# EXPERIMENT B: Single Class Calibration (0-9)
# =========================================================================
print(f"\n--- Running Single Class Ablation ---")
# Use a fixed reasonable size for class calibration (e.g., 100 images of that class)
CLASS_CALIB_SIZE = 100
for class_idx in range(args.num_classes):
try:
# 1. Collect Activations using ONLY 'class_idx'
acts_clean, acts_trig = collect_activations(
model, test_loader, trigger_fn, args.device, layers_to_use,
max_samples=CLASS_CALIB_SIZE, target_class=class_idx
)
# 2. Find Monitor Neurons (Do highly reactive neurons differ by class?)
msb_stats = collect_msb_stats(acts_clean, acts_trig, layers_to_use, top_k=5)
natural_candidates = {
layer: stats['top_filters'].tolist() for layer, stats in msb_stats.items()
}
# 3. Create Detection Set
detection_candidates = create_detection_candidates(picks, natural_candidates, True)
# 4. Evaluate (Eval set remains general/mixed to test robustness)
fp, n_clean = evaluate_msb_only_detector(model, test_loader, layers_to_use, detection_candidates, args.device, max_images=500, apply_trigger=False)
tp, n_trig = evaluate_msb_only_detector(model, test_loader, layers_to_use, detection_candidates, args.device, max_images=500, apply_trigger=True)
tpr = tp / n_trig if n_trig > 0 else 0
fpr = fp / n_clean if n_clean > 0 else 0
results.append({
"experiment": "single_class",
"param_value": class_idx, # Class ID
"tpr": tpr,
"fpr": fpr,
"monitor_candidates": str(natural_candidates)
})
print(f"Class: {class_idx:<2} | TPR: {tpr:.2%} | FPR: {fpr:.2%}")
except Exception as e:
print(f"Error on class {class_idx}: {e}")
return pd.DataFrame(results)
def plot_activation_heatmaps(
acts_clean: Dict[str, List[torch.Tensor]],
acts_trig: Dict[str, List[torch.Tensor]],
layers: List[str],
k: int = 5
):
"""
acts_clean[layer] = list of torch.Tensor [batch_size, C, H, W]
acts_trig [same structure]
layers = list of layer?names you want to plot
k = how many top?shifted filters to show
"""
n = len(layers)
fig, axes = plt.subplots(n, 3,
figsize=(3*4, n*3),
squeeze=False,
tight_layout=True)
for i, layer in enumerate(layers):
# 1) stack into [N, C, H, W]
clean_t = torch.cat(acts_clean[layer], dim=0) # [N, C, H, W]
trig_t = torch.cat(acts_trig[layer], dim=0)
# 2) spatial?mean ? [N, C]
clean_arr = clean_t.mean(dim=(2,3)).cpu().numpy()
trig_arr = trig_t.mean(dim=(2,3)).cpu().numpy()
diff = trig_arr - clean_arr # [N, C]
# 3) mean absolute shift per filter
mean_shift = np.mean(np.abs(diff), axis=0) # [C]
top_idx = np.argsort(-mean_shift)[:k] # top?k filter indices
ax0, ax1, ax2 = axes[i]
im0 = ax0.imshow(clean_arr[:, top_idx], aspect='auto')
ax0.set_title(f"{layer}\nclean")
ax0.set_ylabel("image #")
ax0.set_xticks(range(k))
ax0.set_xticklabels(top_idx, rotation=90)
im1 = ax1.imshow(trig_arr[:, top_idx], aspect='auto')
ax1.set_title("triggered")
ax1.set_xticks(range(k))
ax1.set_xticklabels(top_idx, rotation=90)
im2 = ax2.imshow(diff[:, top_idx], aspect='auto', cmap="bwr")
ax2.set_title("diff = trig ? clean")
ax2.set_xticks(range(k))
ax2.set_xticklabels(top_idx, rotation=90)
# a single colorbar for the diff column
fig.colorbar(im2, ax=ax2, fraction=0.046, pad=0.04)
plt.show()
def detect_trigger_lr(model,
loader,
trigger_fn,
device,
candidates, # dict[layer_name -> list of filter idxs]
test_size=0.5,
random_state=0,
target_fpr=0.05):
"""
Train & eval a logistic?regression detector on mean/std/amax activations
of all filters in `candidates`, comparing clean vs. triggered.
Returns (clf, best_tau, accuracy_at_tau, fpr_at_tau).
"""
model.eval()
# 1) hook all candidate layers