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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from wilds import get_dataset
|
| 2 |
+
from wilds.common.data_loaders import get_train_loader
|
| 3 |
+
import torchvision.transforms as transforms
|
| 4 |
+
import torch
|
| 5 |
+
from wilds.common.grouper import CombinatorialGrouper
|
| 6 |
+
import random
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
import torch.optim as optim
|
| 10 |
+
import torchvision.models as models
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
import wandb
|
| 13 |
+
import argparse
|
| 14 |
+
from torchvision.transforms import functional as Fß
|
| 15 |
+
from torchvision.transforms import v2
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def main():
|
| 19 |
+
parser = argparse.ArgumentParser()
|
| 20 |
+
parser.add_argument('--resize', type=int, default=224,
|
| 21 |
+
help='Size to resize images to (default: 224)')
|
| 22 |
+
parser.add_argument('--seed', type=int, default=1,
|
| 23 |
+
help='Seed for random number generator (default: 1)')
|
| 24 |
+
parser.add_argument('--cuda', type=int, default=1,
|
| 25 |
+
help='CUDA device number (default: 1)')
|
| 26 |
+
parser.add_argument('--auditor_augs', action='store_true', default=False,
|
| 27 |
+
help='Enable auditor augmentations (default: False)')
|
| 28 |
+
parser.add_argument('--auto_aug', action='store_true', default=False,
|
| 29 |
+
help='Enable auto augmentations (default: False)')
|
| 30 |
+
args = parser.parse_args()
|
| 31 |
+
|
| 32 |
+
# set seeds
|
| 33 |
+
random.seed(args.seed)
|
| 34 |
+
torch.manual_seed(args.seed)
|
| 35 |
+
np.random.seed(args.seed)
|
| 36 |
+
|
| 37 |
+
# Initialize wandb
|
| 38 |
+
wandb.init(project="ModelAuditor", name="Camelyon17_ResNet50_" + str(args.seed) + "_" + str(args.resize) + ("_AuditorAugs" if args.auditor_augs else "") + ("_AutoAugs" if args.auto_aug else ""))
|
| 39 |
+
|
| 40 |
+
# Load the full dataset, and download it if necessary
|
| 41 |
+
dataset = get_dataset(dataset="camelyon17", download=True)
|
| 42 |
+
|
| 43 |
+
if args.auditor_augs:
|
| 44 |
+
aug_list = [
|
| 45 |
+
# PUT HERE WHAT THE AUDITOR GIVES YOU
|
| 46 |
+
]
|
| 47 |
+
else:
|
| 48 |
+
aug_list = []
|
| 49 |
+
|
| 50 |
+
# Get the training set
|
| 51 |
+
if args.auto_aug:
|
| 52 |
+
train_data = dataset.get_subset(
|
| 53 |
+
"train",
|
| 54 |
+
transform=transforms.Compose(
|
| 55 |
+
[transforms.Resize((args.resize, args.resize)), transforms.AutoAugment(transforms.AutoAugmentPolicy.IMAGENET)] + aug_list + [transforms.ToTensor(), transforms.Normalize(mean=[.5], std=[.5])]
|
| 56 |
+
),
|
| 57 |
+
)
|
| 58 |
+
else:
|
| 59 |
+
train_data = dataset.get_subset(
|
| 60 |
+
"train",
|
| 61 |
+
transform=transforms.Compose(
|
| 62 |
+
[transforms.Resize((args.resize, args.resize)), transforms.ToTensor()] + aug_list + [transforms.Normalize(mean=[.5], std=[.5])]
|
| 63 |
+
),
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# Load pre-computed groups
|
| 69 |
+
all_groups = torch.from_numpy(np.load('unique_groups.npy'))
|
| 70 |
+
|
| 71 |
+
# Get indices where group is 0
|
| 72 |
+
zero_indices = (all_groups == 0).nonzero().squeeze()
|
| 73 |
+
one_indices = (all_groups == 3).nonzero().squeeze()
|
| 74 |
+
|
| 75 |
+
# Create subset of training data with only group 0 samples
|
| 76 |
+
train_data_zero = torch.utils.data.Subset(train_data, zero_indices)
|
| 77 |
+
train_data_one = torch.utils.data.Subset(train_data, one_indices)
|
| 78 |
+
|
| 79 |
+
# Create data loaders
|
| 80 |
+
train_loader = torch.utils.data.DataLoader(train_data_zero, batch_size=64, shuffle=True, num_workers=8)
|
| 81 |
+
val_loader = torch.utils.data.DataLoader(train_data_one, batch_size=64, num_workers=8)
|
| 82 |
+
|
| 83 |
+
# Randomly sample a subset of validation data
|
| 84 |
+
val_subset_size = 5000 # Adjust this number as needed
|
| 85 |
+
val_indices = random.sample(range(len(train_data_one)), val_subset_size)
|
| 86 |
+
train_data_one = torch.utils.data.Subset(train_data_one, val_indices)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# Set device
|
| 90 |
+
device = torch.device("cuda")
|
| 91 |
+
|
| 92 |
+
# Initialize model, optimizer, criterion
|
| 93 |
+
model = models.resnet50(weights=models.ResNet50_Weights.IMAGENET1K_V1)
|
| 94 |
+
model.fc = nn.Linear(model.fc.in_features, 2)
|
| 95 |
+
model = model.to(device)
|
| 96 |
+
|
| 97 |
+
optimizer = optim.Adam(model.parameters(), lr=0.001)
|
| 98 |
+
criterion = nn.CrossEntropyLoss()
|
| 99 |
+
|
| 100 |
+
# Initialize scaler for mixed precision
|
| 101 |
+
scaler = torch.amp.GradScaler("cuda")
|
| 102 |
+
|
| 103 |
+
# Training parameters
|
| 104 |
+
n_epochs = 10
|
| 105 |
+
|
| 106 |
+
# Add learning rate scheduler
|
| 107 |
+
warmup_epochs = 2
|
| 108 |
+
total_steps = len(train_loader) * n_epochs
|
| 109 |
+
warmup_steps = len(train_loader) * warmup_epochs
|
| 110 |
+
scheduler = optim.lr_scheduler.OneCycleLR(
|
| 111 |
+
optimizer,
|
| 112 |
+
max_lr=0.001,
|
| 113 |
+
total_steps=total_steps,
|
| 114 |
+
pct_start=warmup_steps/total_steps,
|
| 115 |
+
anneal_strategy='cos'
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# Training loop
|
| 121 |
+
for epoch in range(n_epochs):
|
| 122 |
+
# Training phase
|
| 123 |
+
model.train()
|
| 124 |
+
train_loss = 0
|
| 125 |
+
for x, y, _ in tqdm(train_loader, desc=f'Epoch {epoch+1}/{n_epochs}'):
|
| 126 |
+
x, y = x.to(device), y.to(device)
|
| 127 |
+
|
| 128 |
+
optimizer.zero_grad()
|
| 129 |
+
|
| 130 |
+
# Mixed precision training
|
| 131 |
+
with torch.amp.autocast('cuda'):
|
| 132 |
+
outputs = model(x)
|
| 133 |
+
loss = criterion(outputs, y)
|
| 134 |
+
|
| 135 |
+
scaler.scale(loss).backward()
|
| 136 |
+
scaler.step(optimizer)
|
| 137 |
+
scaler.update()
|
| 138 |
+
scheduler.step()
|
| 139 |
+
|
| 140 |
+
train_loss += loss.item()
|
| 141 |
+
|
| 142 |
+
train_loss /= len(train_loader)
|
| 143 |
+
|
| 144 |
+
# Validation phase
|
| 145 |
+
model.eval()
|
| 146 |
+
val_loss = 0
|
| 147 |
+
correct = 0
|
| 148 |
+
total = 0
|
| 149 |
+
|
| 150 |
+
with torch.no_grad():
|
| 151 |
+
for x, y, _ in val_loader:
|
| 152 |
+
x, y = x.to(device), y.to(device)
|
| 153 |
+
with torch.amp.autocast('cuda'):
|
| 154 |
+
outputs = model(x)
|
| 155 |
+
loss = criterion(outputs, y)
|
| 156 |
+
val_loss += loss.item()
|
| 157 |
+
|
| 158 |
+
_, predicted = outputs.max(1)
|
| 159 |
+
total += y.size(0)
|
| 160 |
+
correct += predicted.eq(y).sum().item()
|
| 161 |
+
|
| 162 |
+
val_loss /= len(val_loader)
|
| 163 |
+
accuracy = 100. * correct / total
|
| 164 |
+
|
| 165 |
+
# Log current learning rate
|
| 166 |
+
current_lr = scheduler.get_last_lr()[0]
|
| 167 |
+
wandb.log({
|
| 168 |
+
"train_loss": train_loss,
|
| 169 |
+
"val_loss": val_loss,
|
| 170 |
+
"val_accuracy": accuracy,
|
| 171 |
+
"epoch": epoch + 1,
|
| 172 |
+
"learning_rate": current_lr
|
| 173 |
+
})
|
| 174 |
+
|
| 175 |
+
print(f'Epoch {epoch+1}: Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Acc: {accuracy:.2f}%')
|
| 176 |
+
|
| 177 |
+
# Save model after each epoch
|
| 178 |
+
torch.save(model.state_dict(), 'camelyon17_resnet50_' + str(args.seed) + '_' + str(args.resize) + ("_AuditorAugs" if args.auditor_augs else "") + ("_AutoAugs" if args.auto_aug else "") + '.pt')
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
if __name__ == "__main__":
|
| 182 |
+
main()
|
| 183 |
+
|