strategies tested
This commit is contained in:
@@ -2,6 +2,9 @@
|
||||
import torch.nn as nn
|
||||
import time
|
||||
import os
|
||||
from pathlib import Path
|
||||
from torch.utils.data import DataLoader
|
||||
import Util
|
||||
|
||||
class Strategy:
|
||||
"""Abstract base class for unlearning algorithms with automated, strategy-specific logging."""
|
||||
@@ -9,21 +12,10 @@ class Strategy:
|
||||
def __init__(self):
|
||||
# Dynamically set file name based on the class name (e.g., 'NormalizingLinearFiltration.txt')
|
||||
self.strategy_name = self.__class__.__name__
|
||||
self.log_file = f"reports/{self.strategy_name}/metrics.txt"
|
||||
self._initialize_log_file()
|
||||
self.log_file = Path(f"reports/{self.strategy_name}/metrics.txt")
|
||||
Util._initialize_log_file(log_file= self.log_file)
|
||||
|
||||
def _initialize_log_file(self):
|
||||
"""Creates a unique log file for this strategy with a header if it doesn't exist."""
|
||||
if not os.path.exists(self.log_file):
|
||||
with open(self.log_file, "w") as f:
|
||||
f.write("execution_time_sec\n")
|
||||
|
||||
def log_metric(self, execution_time: float):
|
||||
"""Appends the execution time to this strategy's specific file."""
|
||||
with open(self.log_file, "a") as f:
|
||||
f.write(f"{execution_time:.6f}\n")
|
||||
|
||||
def apply(self, model: nn.Module) -> nn.Module:
|
||||
def apply(self, model: nn.Module, forget_loader: DataLoader, retain_loader: DataLoader) -> nn.Module:
|
||||
"""
|
||||
Wraps the unlearning execution with automated timing and strategy-specific logging.
|
||||
DO NOT override this method in subclasses. Override _run instead.
|
||||
@@ -31,17 +23,21 @@ class Strategy:
|
||||
start_time = time.perf_counter()
|
||||
|
||||
# Execute core unlearning logic
|
||||
processed_model = self._run(model)
|
||||
processed_model = self._run(model, forget_loader, retain_loader)
|
||||
|
||||
end_time = time.perf_counter()
|
||||
execution_time = end_time - start_time
|
||||
|
||||
# Log to the strategy's specific file
|
||||
self.log_metric(execution_time)
|
||||
Util.log_metric(
|
||||
log_file=self.log_file,
|
||||
execution_time=execution_time
|
||||
)
|
||||
|
||||
print(f"[{self.strategy_name}] Completed in {execution_time:.6f} seconds. Saved to {self.log_file}")
|
||||
|
||||
return processed_model
|
||||
|
||||
def _run(self, model: nn.Module) -> nn.Module:
|
||||
def _run(self, model: nn.Module, forget_loader: DataLoader, retain_loader: DataLoader) -> nn.Module:
|
||||
"""Subclasses implement their core unlearning logic here."""
|
||||
raise NotImplementedError
|
||||
Reference in New Issue
Block a user