-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmethods.py
More file actions
1654 lines (1440 loc) · 63.5 KB
/
Copy pathmethods.py
File metadata and controls
1654 lines (1440 loc) · 63.5 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.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
from tqdm import tqdm
import numpy as np
import models
from typing import Tuple, Dict, List
import logging
from torch.optim.lr_scheduler import (
CosineAnnealingLR,
CosineAnnealingWarmRestarts,
StepLR,
)
from torch.utils.data import Dataset, Subset
from torch.optim.lr_scheduler import _LRScheduler
import os
import torchvision
# from opts import OPT as opt
import pickle
from utils import accuracy
import time
from copy import deepcopy
import itertools
import copy
class UnlearningMethods:
def __init__(self, model: nn.Module, learning_rate: float = 0.01):
"""
Initialize unlearning methods
Args:
model: Neural network model
forget_class: Class index to forget
learning_rate: Learning rate for unlearning
"""
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model = model.to(self.device)
self.learning_rate = learning_rate
print(f"Using device: {self.device}")
def _monitor_progress(self, loader: DataLoader, epoch: int) -> None:
"""Monitor prediction distribution during unlearning"""
self.model.eval()
with torch.no_grad():
all_probs = []
for data, _ in loader:
data = data.to(self.device)
output = F.softmax(self.model(data), dim=1)
all_probs.append(output)
all_probs = torch.cat(all_probs, dim=0)
avg_probs = all_probs.mean(dim=0)
print(f"\nEpoch {epoch+1} prediction distribution:")
for i, prob in enumerate(avg_probs):
print(f"Class {i}: {prob.item()*100:.2f}%")
self.model.train()
def evaluate(
self, test_loader: DataLoader, num_classes: int = 100
) -> Tuple[float, Dict[int, float], Dict[int, np.ndarray]]:
"""
Evaluate model performance for each class
Returns:
Tuple of (overall_accuracy, class_accuracy, prediction_distribution)
"""
self.model.eval()
class_correct = [0] * num_classes
class_total = [0] * num_classes
class_predictions = [[] for _ in range(num_classes)]
with torch.no_grad():
for data, targets in tqdm(test_loader):
data, targets = data.to(self.device), targets.to(self.device)
outputs = self.model(data)
_, predicted = outputs.max(1)
for i in range(len(targets)):
label = targets[i].item()
pred = predicted[i].item()
class_total[label] += 1
if label == pred:
class_correct[label] += 1
class_predictions[label].append(pred)
class_accuracy = {}
prediction_distribution = {}
correct = 0
total = 0
overall_accuracy = 0
for i in range(len(class_total)):
if class_total[i] > 0:
correct += class_correct[i]
total += class_total[i]
accuracy = 100.0 * class_correct[i] / class_total[i]
predictions = class_predictions[i]
dist = np.bincount(predictions, minlength=num_classes) / len(
predictions
)
class_accuracy[i] = accuracy
prediction_distribution[i] = dist
overall_accuracy = 100.0 * correct / total
return overall_accuracy, class_accuracy, prediction_distribution
def retrain_learning(
self,
seed: int,
forget_class: int,
train_retain_loader: DataLoader,
test_forget_loader: DataLoader,
test_retain_loader: DataLoader,
num_epochs: int = 5,
save_path: str = None,
) -> None:
# optimizer = optim.Adam(self.model.parameters(), lr=self.learning_rate)
# Adam optimiser does not work for this task
# use SGD
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(
self.model.parameters(),
lr=self.learning_rate,
momentum=0.9,
weight_decay=5e-4,
nesterov=True,
)
cosine = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=num_epochs)
best_acc = 0
# Training progress bar
for epoch in tqdm(range(num_epochs)):
self.model.train()
train_correct = 0
train_total = 0
train_loss = 0
train_pbar = tqdm(
train_retain_loader, desc=f"Epoch {epoch+1}/{num_epochs} [Train]"
)
for data, target in train_pbar:
data, target = data.to(self.device), target.to(self.device)
optimizer.zero_grad()
output = self.model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
# Calculate training accuracy
_, predicted = torch.max(output.data, 1)
train_total += target.size(0)
train_correct += (predicted == target).sum().item()
train_loss += loss.item()
# Update progress bar
train_pbar.set_postfix(
{
"loss": f"{train_loss/(train_pbar.n+1):.4f}",
"acc": f"{100.*train_correct/train_total:.2f}%",
}
)
cosine.step()
# Evaluate on test retain set only (gold model is trained only on retain data)
self.model.eval()
test_retain_correct = 0
test_retain_total = 0
with torch.no_grad():
for data, target in test_retain_loader:
data, target = data.to(self.device), target.to(self.device)
output = self.model(data)
_, predicted = torch.max(output.data, 1)
test_retain_total += target.size(0)
test_retain_correct += (predicted == target).sum().item()
test_retain_acc = 100.0 * test_retain_correct / test_retain_total
# Print epoch summary
train_acc = 100.0 * train_correct / train_total
tqdm.write(f"\nEpoch {epoch+1}/{num_epochs}:")
tqdm.write(
f"Train Loss: {train_loss/len(train_retain_loader):.4f}, Train Acc: {train_acc:.2f}%, Test Retain Acc: {test_retain_acc:.2f}%"
)
logging.info(
f"Epoch{epoch+1}'s loss: {train_loss/len(train_retain_loader):.4f}, Train Acc: {train_acc:.2f}%, Test Retain Acc: {test_retain_acc:.2f}%"
)
# Save best model
if test_retain_acc > best_acc:
best_acc = test_retain_acc
if not os.path.exists(f"outputs/seed{seed}/models"):
os.makedirs(f"outputs/seed{seed}/models")
torch.save(
self.model.state_dict(),
f"outputs/seed{seed}/models/cifar10_forget{forget_class}_gold_model_best.pth",
)
tqdm.write(
f"Saved best model with validation accuracy: {best_acc:.2f}%"
)
tqdm.write("-" * 60)
# Save final model
if save_path:
# Use provided save path with _final suffix
save_dir = os.path.dirname(save_path)
final_save_path = save_path.replace(".pth", "_final.pth")
if not os.path.exists(save_dir):
os.makedirs(save_dir)
torch.save(self.model.state_dict(), final_save_path)
else:
# Fallback to original behavior
torch.save(
self.model.state_dict(),
f"outputs/seed{seed}/models/cifar10_forget{forget_class}_gold_model_final.pth",
)
# return best_acc
def vanilla_unlearning(
self, forget_loader: DataLoader, retain_loader: DataLoader, num_epochs: int = 5
) -> None:
"""Simple entropy maximization unlearning"""
self.model.train()
# optimizer = optim.Adam(self.model.parameters(), lr=self.learning_rate)
# Adam optimiser does not work for this task
# use SGD
optimizer = optim.SGD(
self.model.parameters(), lr=self.learning_rate, momentum=0.9
)
for epoch in range(num_epochs):
total_entropy = 0
train_loss = 0
batch_count = 0
pbar = tqdm(
forget_loader, desc=f"Vanilla Unlearning Epoch {epoch+1}/{num_epochs}"
)
for data, _ in pbar:
data = data.to(self.device)
optimizer.zero_grad()
outputs = self.model(data)
# Maximize entropy
probs = F.softmax(outputs, dim=1)
entropy = -(probs * torch.log(probs + 1e-10)).sum(dim=1).mean()
loss = -entropy
loss.backward()
optimizer.step()
total_entropy += entropy.item()
pbar.set_postfix({"entropy": f"{entropy.item():.4f}"})
train_loss += loss.item()
batch_count += 1
avg_loss = train_loss / batch_count
logging.info(f"Epoch{epoch}'s loss: {avg_loss:.4f}")
avg_entropy = total_entropy / len(forget_loader)
print(f"Epoch {epoch+1}/{num_epochs}, Average Entropy: {avg_entropy:.4f}")
# self._monitor_progress(forget_loader, epoch)
def finetuning_unlearning(
self, forget_loader: DataLoader, retain_loader: DataLoader, num_epochs: int = 50
) -> None:
"""Simple entropy maximization unlearning"""
self.model.train()
# optimizer = optim.Adam(self.model.parameters(), lr=self.learning_rate)
# Adam optimiser does not work for this task
# use SGD
optimizer = optim.SGD(
self.model.parameters(), lr=self.learning_rate, momentum=0.9
)
criterion = nn.CrossEntropyLoss()
for epoch in range(num_epochs):
train_loss = 0
batch_count = 0
pbar = tqdm(retain_loader, desc=f"Fine-tuning Epoch {epoch+1}/{num_epochs}")
for data, target in pbar:
data = data.to(self.device)
target = target.to(self.device)
optimizer.zero_grad()
outputs = self.model(data)
loss = criterion(outputs, target)
loss.backward()
optimizer.step()
train_loss += loss.item()
batch_count += 1
avg_loss = train_loss / batch_count
logging.info(f"Epoch{epoch}'s loss: {avg_loss:.4f}")
# self._monitor_progress(forget_loader, epoch)
def ETF_replace(
self,
forget_loader: DataLoader,
retain_loader: DataLoader,
forget_class: int,
) -> None:
"""
ETF (Equiangular Tight Frame) replacement unlearning method.
Assumes the model classifier has reached ETF structure and eliminates
the forget class by applying an orthogonal transformation to the
vector corresponding to the forgetting class.
Args:
forget_loader: DataLoader for forget set
retain_loader: DataLoader for retain set
forget_class: Class index to forget
"""
self.model.train()
# Get the classifier weights (assuming it's the last layer)
classifier = None
for name, module in self.model.named_modules():
if isinstance(module, nn.Linear) and name.endswith(
(".fc", ".classifier", ".head")
):
classifier = module
break
if classifier is None:
# Try to find the last linear layer
for name, module in reversed(list(self.model.named_modules())):
if isinstance(module, nn.Linear):
classifier = module
break
if classifier is None:
raise ValueError("Could not find classifier layer in the model")
print(f"Found classifier: {classifier}")
print(f"Classifier weight shape: {classifier.weight.shape}")
# Get the current weight matrix
W = classifier.weight.data.clone() # Shape: [num_classes, feature_dim]
num_classes, feature_dim = W.shape
# Normalize the weight vectors to unit length
W_norm = F.normalize(W, p=2, dim=1)
# Get the forget class vector
forget_vector = W_norm[forget_class] # Shape: [feature_dim]
# Create a projection matrix to remove the forget class component
# from all other class vectors
def create_projection_matrix(forget_vector, feature_dim):
"""
Create a projection matrix P = I - vv^T/||v||^2 that projects out
the component along the forget vector from any vector
"""
v = F.normalize(forget_vector, p=2, dim=0)
# P = I - vv^T
P = torch.eye(feature_dim, device=self.device) - torch.outer(v, v)
return P
# Create projection matrix
P = create_projection_matrix(forget_vector, feature_dim)
# Apply projection to all other class vectors to remove forget class component
new_W = W.clone()
for i in range(num_classes):
if i != forget_class:
# Project out the forget class component from this class vector
projected_vector = torch.matmul(P, W[i])
new_W[i] = projected_vector
# Set forget class vector to zero
new_W[forget_class] = torch.zeros_like(W[forget_class])
# Update the classifier weights
with torch.no_grad():
classifier.weight.data.copy_(new_W)
# Also zero out the bias for the forget class if it exists
if classifier.bias is not None:
classifier.bias.data[forget_class] = 0.0
print(f"Applied projection-based transformation to forget class {forget_class}")
print(
f"Original forget vector norm: {torch.norm(W_norm[forget_class], p=2):.4f}"
)
print(f"New forget vector norm: {torch.norm(new_W[forget_class], p=2):.4f}")
# Additional analysis: Check if the model still has information about forget class
print(
f"\nForget class vector is now zero: {torch.allclose(new_W[forget_class], torch.zeros_like(new_W[forget_class]))}"
)
if classifier.bias is not None:
print(
f"Forget class bias is now zero: {classifier.bias.data[forget_class] == 0.0}"
)
# Verify that other class vectors are orthogonal to forget class vector
new_W_norm = F.normalize(new_W, p=2, dim=1)
print("\nVerifying orthogonality after projection:")
for i in range(num_classes):
if i != forget_class:
dot_product = torch.dot(new_W_norm[forget_class], new_W_norm[i])
print(f"Dot product with class {i}: {dot_product:.6f}")
# Check the rank of the transformed weight matrix
rank = torch.linalg.matrix_rank(new_W)
print(
f"\nRank of transformed weight matrix: {rank} (should be {num_classes-1})"
)
self.model.eval()
def _find_classifier(self) -> nn.Linear:
# Try common names first
classifier = None
for name, module in self.model.named_modules():
if isinstance(module, nn.Linear) and name.endswith(
(".fc", ".classifier", ".head")
):
classifier = module
break
if classifier is None:
# Fallback: last Linear in the network
for name, module in reversed(list(self.model.named_modules())):
if isinstance(module, nn.Linear):
classifier = module
break
if classifier is None:
raise ValueError("Could not find classifier (nn.Linear) in the model.")
return classifier
@torch.no_grad()
def _build_etf_projection(self, w_forget: torch.Tensor) -> torch.Tensor:
"""
Make P = I - v v^T where v = normalized forget vector (dim=D).
"""
v = F.normalize(w_forget, p=2, dim=0)
D = v.numel()
P = torch.eye(D, device=self.device) - torch.outer(v, v)
return P
def _capture_features(
self, model: nn.Module, x: torch.Tensor, classifier: nn.Linear, detach: bool
) -> torch.Tensor:
"""
Capture the input to the classifier (penultimate features) via a forward hook.
If detach=True, returns a detached tensor (for teacher/targets).
"""
feats = {}
def hook(m, inputs, output):
# inputs is a tuple; the first item is the feature tensor [B, D]
feats["f"] = inputs[0] if not detach else inputs[0].detach()
handle = classifier.register_forward_hook(hook)
_ = model(x) # forward pass triggers the hook
handle.remove()
if "f" not in feats:
raise RuntimeError("Failed to capture features. Hook did not run.")
return feats["f"]
def _compute_etf_loss(
self, student_features: torch.Tensor, targets: torch.Tensor, loss_function: str
) -> torch.Tensor:
"""
Compute loss between student features and ETF-projected targets.
Args:
student_features: features from student model [B, D]
targets: ETF-projected target features [B, D]
loss_function: type of loss to compute
Returns:
loss tensor
"""
if loss_function == "cosine":
# Original cosine similarity loss (can be unstable)
f_s_n = F.normalize(student_features, p=2, dim=1)
targets_n = F.normalize(targets, p=2, dim=1)
cos_sim = (f_s_n * targets_n).sum(dim=1)
return 1.0 - cos_sim.mean()
elif loss_function == "mse_normalized":
# MSE between normalized vectors (more stable)
f_s_n = F.normalize(student_features, p=2, dim=1)
targets_n = F.normalize(targets, p=2, dim=1)
return F.mse_loss(f_s_n, targets_n)
elif loss_function == "l2_regression":
# Direct L2 regression without normalization
return F.mse_loss(student_features, targets)
elif loss_function == "huber":
# Huber (smooth L1) loss - robust against outliers
return F.smooth_l1_loss(student_features, targets)
elif loss_function == "angular":
# Angular distance loss (arccos of cosine similarity)
f_s_n = F.normalize(student_features, p=2, dim=1)
targets_n = F.normalize(targets, p=2, dim=1)
cos_sim = (f_s_n * targets_n).sum(dim=1)
# Clamp to avoid numerical issues with arccos
cos_sim = torch.clamp(cos_sim, -1.0 + 1e-7, 1.0 - 1e-7)
return torch.acos(cos_sim).mean()
else:
raise ValueError(
f"Unknown loss function: {loss_function}. "
f"Supported options: cosine, mse_normalized, l2_regression, huber, angular"
)
# ---------- main method ----------
def etf_finetune(
self,
retain_loader: DataLoader = None,
forget_class: int = 0,
num_epochs: int = 20,
freeze_classifier: bool = True,
freeze_bn_stats: bool = True,
log_every: int = 50,
loss_function: str = "l2_regression",
forget_loader: DataLoader = None,
) -> None:
"""
Fine-tune the feature extractor so its features match ETF-projected features.
Steps:
1) Build projection P = I - v v^T using v = normalized classifier weight of the forget class.
2) Create a frozen teacher model T that produces target features f_T(x); targets = P f_T(x).
3) Optimize original model's backbone to match its features to targets using specified loss.
Args:
retain_loader: deprecated; not used in this method.
forget_loader: forget data loader to use for fine-tuning (required)
forget_class: index of the class to forget (used to form the projection)
num_epochs: fine-tuning epochs
freeze_classifier: if True, do not update classifier weights/bias
freeze_bn_stats: if True, run teacher in eval() and also set BN in student to eval() during training
log_every: steps per logging
loss_function: loss function to use for feature alignment. Options:
- "cosine": 1 - cosine_similarity (original, can be unstable)
- "mse_normalized": MSE between normalized vectors (more stable)
- "l2_regression": direct L2 loss without normalization
- "huber": smooth L1 loss (robust against outliers)
- "angular": arccos of cosine similarity (smoother than cosine)
"""
self.model.train()
# 1) locate classifier and build projection
classifier = self._find_classifier()
with torch.no_grad():
W = classifier.weight.data.clone() # [C, D]
v_forget = F.normalize(W[forget_class], p=2, dim=0) # [D]
P = self._build_etf_projection(v_forget) # [D, D]
# 2) frozen teacher model (same weights now)
teacher = copy.deepcopy(self.model).to(self.device)
for p in teacher.parameters():
p.requires_grad_(False)
teacher.eval()
# 3) prepare optimizer over *feature extractor only*
# freeze classifier if requested
if freeze_classifier:
for p in classifier.parameters():
p.requires_grad_(False)
# optionally freeze BN running-stat updates in the student
if freeze_bn_stats:
# Put student in train mode but freeze BN stats by forcing BN layers to eval
self.model.train()
for m in self.model.modules():
if isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d)):
m.eval() # no running stat updates
# pick params that require grad
params = [p for p in self.model.parameters() if p.requires_grad]
if len(params) == 0:
raise ValueError("No trainable parameters selected for fine-tuning.")
optimizer = optim.SGD(
params,
lr=self.learning_rate,
momentum=0.9,
weight_decay=5e-4,
nesterov=True,
)
scheduler = CosineAnnealingLR(optimizer, T_max=num_epochs)
step = 0
# strictly use forget_loader; retain data must not be used here
actual_loader = forget_loader
if actual_loader is None:
raise ValueError(
"etf_finetune requires forget_loader (retain data is not used)."
)
for epoch in range(num_epochs):
pbar = tqdm(
actual_loader, desc=f"ETF-Finetune Epoch {epoch+1}/{num_epochs}"
)
running_loss, running_sim = 0.0, 0.0
for i, (x, _) in enumerate(pbar):
x = x.to(self.device)
# teacher targets: f_T(x) -> P f_T(x)
with torch.no_grad():
teacher_cls = None
# find teacher's classifier (same structure)
for name, module in teacher.named_modules():
if isinstance(module, nn.Linear) and name.endswith(
(".fc", ".classifier", ".head")
):
teacher_cls = module
break
if teacher_cls is None:
for name, module in reversed(list(teacher.named_modules())):
if isinstance(module, nn.Linear):
teacher_cls = module
break
f_t = self._capture_features(
teacher, x, teacher_cls, detach=True
) # [B, D]
targets = f_t @ P.T # [B, D]
# student features (need grads)
f_s = self._capture_features(
self.model, x, classifier, detach=False
) # [B, D]
# compute loss using specified loss function
loss = self._compute_etf_loss(f_s, targets, loss_function)
optimizer.zero_grad()
loss.backward()
optimizer.step()
running_loss += loss.item()
# compute cosine similarity for logging (regardless of loss function)
with torch.no_grad():
f_s_n = F.normalize(f_s, p=2, dim=1)
targets_n = F.normalize(targets, p=2, dim=1)
cos_sim = (f_s_n * targets_n).sum(dim=1).mean().item()
running_sim += cos_sim
step += 1
if (i + 1) % log_every == 0:
avg_loss = running_loss / log_every
avg_sim = running_sim / log_every
pbar.set_postfix(
{"loss": f"{avg_loss:.4f}", "cos_sim": f"{avg_sim:.4f}"}
)
logging.info(
f"[ETF-Finetune] epoch {epoch+1} step {i+1}: loss={avg_loss:.4f} ({loss_function}), cos_sim={avg_sim:.4f}"
)
running_loss, running_sim = 0.0, 0.0
scheduler.step()
# restore classifier grad flags (optional—only if you want to resume normal training later)
if freeze_classifier:
for p in classifier.parameters():
p.requires_grad_(True)
def random_label_unlearning(
self,
forget_loader: DataLoader,
retain_loader: DataLoader,
num_epochs: int = 1,
noise_scale: float = 0.1,
) -> None:
"""Unlearning by training on randomly labeled forget set data"""
self.model.train()
optimizer = optim.SGD(
self.model.parameters(), lr=self.learning_rate, momentum=0.9
)
criterion = nn.CrossEntropyLoss()
for epoch in range(num_epochs):
train_loss = 0
batch_count = 0
# Train on forget set with random labels
pbar = tqdm(
forget_loader,
desc=f"Random Label Unlearning Epoch {epoch+1}/{num_epochs}",
)
for data, _ in pbar:
data = data.to(self.device)
batch_size = data.size(0)
# Generate random labels for forget set (0-8 for PathMNIST)
random_labels = torch.randint(0, 9, (batch_size,), device=self.device)
# random number 2 or 8
# random_labels = torch.randint(2, 8, (batch_size,), device=self.device)
optimizer.zero_grad()
# noisy_data = data + torch.randn_like(data) * noise_scale
outputs = self.model(data)
loss = criterion(outputs, random_labels)
loss.backward()
optimizer.step()
train_loss += loss.item()
batch_count += 1
# Update progress bar
pbar.set_postfix({"loss": f"{loss.item():.4f}"})
"""
# Train on retain set with correct labels
for data, labels in retain_loader:
data, labels = data.to(self.device), labels.to(self.device)
optimizer.zero_grad()
outputs = self.model(data)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
train_loss += loss.item()
batch_count += 1
"""
# Monitor progress
avg_loss = train_loss / batch_count
self._monitor_progress(retain_loader, epoch)
tqdm.write(f"\nEpoch {epoch+1}/{num_epochs}:")
tqdm.write(f"Average Loss: {avg_loss:.4f}")
tqdm.write("-" * 60)
def upper_bound_unlearning(
self,
train_forget_loader: DataLoader,
train_retain_loader: DataLoader,
test_forget_loader: DataLoader,
test_retain_loader: DataLoader,
num_epochs: int = 5,
) -> None:
"""
Upper bound unlearning method that trains a 9-class model on 9 classes.
This is the corrected version of the gold method that fixes the output dimension mismatch.
"""
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(
self.model.parameters(),
lr=self.learning_rate,
momentum=0.9,
weight_decay=5e-4,
nesterov=True,
)
cosine = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=num_epochs)
best_acc = 0
# Training progress bar
for epoch in tqdm(range(num_epochs)):
self.model.train()
train_correct = 0
train_total = 0
train_loss = 0
train_pbar = tqdm(
train_retain_loader,
desc=f"Epoch {epoch+1}/{num_epochs} [Upper Bound Train]",
)
for data, target in train_pbar:
data, target = data.to(self.device), target.to(self.device)
optimizer.zero_grad()
output = self.model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
# Calculate training accuracy
_, predicted = torch.max(output.data, 1)
train_total += target.size(0)
train_correct += (predicted == target).sum().item()
train_loss += loss.item()
# Update progress bar
train_pbar.set_postfix(
{
"loss": f"{train_loss/(train_pbar.n+1):.4f}",
"acc": f"{100.*train_correct/train_total:.2f}%",
}
)
cosine.step()
# Evaluate on test set
self.model.eval()
test_retain_correct = 0
test_retain_total = 0
with torch.no_grad():
for data, target in test_retain_loader:
data, target = data.to(self.device), target.to(self.device)
output = self.model(data)
_, predicted = torch.max(output.data, 1)
test_retain_total += target.size(0)
test_retain_correct += (predicted == target).sum().item()
test_retain_acc = 100.0 * test_retain_correct / test_retain_total
# Print epoch summary
train_acc = 100.0 * train_correct / train_total
tqdm.write(f"\nEpoch {epoch+1}/{num_epochs}:")
tqdm.write(
f"Train Loss: {train_loss/len(train_retain_loader):.4f}, Train Acc: {train_acc:.2f}%, Test Retain Acc: {test_retain_acc:.2f}%"
)
logging.info(
f"Epoch{epoch+1}'s loss: {train_loss/len(train_retain_loader):.4f}, Train Acc: {train_acc:.2f}%, Test Retain Acc: {test_retain_acc:.2f}%"
)
tqdm.write("-" * 60)
tqdm.write("Upper bound unlearning completed successfully!")
logging.info("Upper bound unlearning completed successfully!")
def boundary_shrink_unlearning(
self,
forget_loader: DataLoader,
num_classes: int,
epsilon: float = 5, # step size for crossing boundary (image inputs in [0,1])
epochs: int = 5, # few epochs typically suffice
lr: float = 1e-3, # fine-tune LR (head-only by default)
head_only: bool = True, # train only classifier head to avoid collateral drift
clamp_min: float = 0.0, # clamp inputs after FGSM
clamp_max: float = 1.0,
momentum: float = 0.9,
weight_decay: float = 0.0,
adv_batch_size: int = None, # optional smaller batch for FGSM gen if memory tight
) -> None:
"""
Boundary Shrink unlearning:
1) For each forget sample x, take an FGSM step across the boundary.
2) Relabel x to the model's predicted (incorrect) class of the adversarial point.
3) Fine-tune on (x, new_label) to shrink the forget region.
Args:
forget_loader: DataLoader over forget set D_f (with true labels, but we'll relabel)
num_classes: total number of classes
epsilon: FGSM magnitude to cross the boundary
epochs: #epochs to fine-tune on relabeled forget set
lr: learning rate for fine-tune
head_only: if True, only optimize the final linear classifier
clamp_min/max: clamp bounds for perturbed inputs
adv_batch_size: if set, regenerates a loader with this batch size for FGSM step
"""
self.model.eval()
# ---- 1) Generate nearest-boundary adversarial points and new labels ----
criterion = nn.CrossEntropyLoss(reduction="mean")
# Optionally rebuild a loader for FGSM to control memory
gen_loader = forget_loader
if adv_batch_size is not None:
gen_loader = DataLoader(
forget_loader.dataset, batch_size=adv_batch_size, shuffle=False
)
new_images = []
new_targets = []
for data, y_true in tqdm(gen_loader, desc="Generating cross-boundary labels"):
data = data.to(self.device)
y_true = y_true.to(self.device)
# require grad on inputs for FGSM
data_adv = data.clone().detach().requires_grad_(True)
logits = self.model(data_adv)
loss = criterion(logits, y_true)
self.model.zero_grad(set_to_none=True)
loss.backward()
# FGSM step across the boundary
x_adv = data_adv + epsilon * data_adv.grad.sign()
x_adv = torch.clamp(x_adv.detach(), clamp_min, clamp_max)
# predict label of adversarial sample (nearest-but-incorrect)
with torch.no_grad():
pred_adv = self.model(x_adv).argmax(dim=1)
# We keep the ORIGINAL images but use the adversarial label (per paper heuristic)
new_images.append(data.detach().cpu())
new_targets.append(pred_adv.detach().cpu())
X = torch.cat(new_images, dim=0)
Y = torch.cat(new_targets, dim=0)
D_shrink = torch.utils.data.TensorDataset(X, Y)
shrink_loader = DataLoader(
D_shrink, batch_size=forget_loader.batch_size, shuffle=True
)
# ---- 2) Fine-tune on relabeled forget set to shrink decision region ----
# Find classifier head if training head-only
params = list(self.model.parameters())
train_params = params
if head_only:
# try to guess the final linear layer
classifier = None
last_linear = None
for name, m in self.model.named_modules():
if isinstance(m, nn.Linear):
last_linear = m
classifier = last_linear
if classifier is None:
raise ValueError(
"BoundaryShrink: couldn't find a final nn.Linear layer for head_only=True."
)
# freeze all except head
for p in self.model.parameters():
p.requires_grad = False
for p in classifier.parameters():
p.requires_grad = True
train_params = [p for p in classifier.parameters() if p.requires_grad]
self.model.train()
optimizer = optim.SGD(
train_params, lr=lr, momentum=momentum, weight_decay=weight_decay
)
for ep in range(epochs):
ep_loss = 0.0
n_batches = 0
pbar = tqdm(
shrink_loader, desc=f"Boundary Shrink fine-tune {ep+1}/{epochs}"
)
for x, y in pbar:
x = x.to(self.device)
y = y.to(self.device)
optimizer.zero_grad(set_to_none=True)
out = self.model(x)
loss = criterion(out, y)
loss.backward()
optimizer.step()
ep_loss += loss.item()
n_batches += 1
pbar.set_postfix({"loss": f"{ep_loss/max(n_batches,1):.4f}"})
# unfreeze if we froze
if head_only:
for p in self.model.parameters():
p.requires_grad = True
self.model.eval()
def delete_unlearning(
self,
forget_loader: DataLoader,
num_classes: int,
epochs: int = 5,
lr: float = 1e-3,
fix_head: bool = True,
temperature: float = 1.0, # distillation temperature
momentum: float = 0.9,
weight_decay: float = 0.0,
) -> None:
"""
DELETE: Decoupled Distillation To Erase (mask-distillation on teacher logits).
- Freeze a copy of the original model as teacher.
- For each batch from the FORGET set, mask forget-class logits on the teacher,
renormalize (softmax), and distill to the current model.
- Optimizes forgetting + retention simultaneously, using only D_f.
Args:
forget_loader: DataLoader over D_f (contains (x, y) with y the class to forget for each sample)
num_classes: total number of classes
epochs: fine-tuning epochs on D_f
lr: learning rate
fix_head: freeze the final linear layer if True
temperature: distillation temperature
"""
# 1) Make a frozen teacher (original model snapshot at start)
import copy
teacher = copy.deepcopy(self.model).to(self.device)
for p in teacher.parameters():
p.requires_grad = False
teacher.eval()
# 2) Optionally fix the head (freeze final linear layer)
train_params = list(self.model.parameters())
classifier = None
if fix_head:
last_linear = None
for name, m in self.model.named_modules():
if isinstance(m, nn.Linear):
last_linear = m
classifier = last_linear
if classifier is None:
raise ValueError(
"DELETE: couldn't find a final nn.Linear for fix_head=True."
)
# Freeze only the head (final linear layer)
for p in classifier.parameters():