"""The ONE fine-tuning recipe used for every model in the paper. Plain words: start from the model trained on GrainSet, then keep training ALL of its layers on a labelled part of GrainDet for 10 epochs with a small learning rate, so it adapts without forgetting what it learned. Every model gets exactly the same settings, so differences between models reflect the models and not the recipe. Settings (paper, Section 4.2): SGD, learning rate 1e-4, momentum 0.9, weight decay 1e-4, cosine learning-rate schedule, batch size 64, gradient clipping at 5, mixed precision on a GPU. Keep the epoch with the best validation macro-F1 ("best_val"), or the last epoch ("last"). """ import copy import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader from .metrics import macro_f1 EPOCHS, LR, MOMENTUM, WEIGHT_DECAY, GRAD_CLIP, BATCH_SIZE = 10, 1e-4, 0.9, 1e-4, 5.0, 64 def predict(model, loader, device): """Run the model on every crop of `loader`. Returns (labels, predicted classes, probabilities).""" model.eval() labels, probs = [], [] with torch.no_grad(): for images, y, _ in loader: logits = model(images.to(device)) probs.append(torch.softmax(logits.float(), dim=1).cpu().numpy()) labels.append(y.numpy()) probs = np.concatenate(probs) return np.concatenate(labels), probs.argmax(1), probs def finetune(model, train_set, val_set, device, epochs=EPOCHS, keep="best_val", seed=509, sample_weights=None, class_weights=None): """Fine-tune `model` in place and return it (with the kept weights loaded). sample_weights / class_weights are only for the imbalance experiment (paper, Section 10): sample_weights -> class-balanced sampling; class_weights -> class-weighted loss. """ torch.manual_seed(seed) model.to(device) if sample_weights is not None: # draw crops with the given probability, same number per epoch sampler = torch.utils.data.WeightedRandomSampler(torch.as_tensor(sample_weights, dtype=torch.double), len(train_set), replacement=True, generator=torch.Generator().manual_seed(seed)) train_loader = DataLoader(train_set, batch_size=BATCH_SIZE, sampler=sampler, drop_last=True, num_workers=2) else: train_loader = DataLoader(train_set, batch_size=BATCH_SIZE, shuffle=True, drop_last=True, num_workers=2) val_loader = DataLoader(val_set, batch_size=BATCH_SIZE, shuffle=False, num_workers=2) loss_fn = nn.CrossEntropyLoss(weight=None if class_weights is None else torch.tensor(class_weights, dtype=torch.float32, device=device)) optimizer = torch.optim.SGD(model.parameters(), lr=LR, momentum=MOMENTUM, weight_decay=WEIGHT_DECAY) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs) use_amp = device.type == "cuda" scaler = torch.amp.GradScaler("cuda", enabled=use_amp) best_score, best_state = -1.0, None for epoch in range(1, epochs + 1): model.train() for images, y, _ in train_loader: images, y = images.to(device), y.to(device) optimizer.zero_grad(set_to_none=True) with torch.autocast(device_type=device.type, enabled=use_amp): loss = loss_fn(model(images), y) scaler.scale(loss).backward() scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), GRAD_CLIP) # stop one bad batch from breaking the model scaler.step(optimizer) scaler.update() scheduler.step() y_val, pred_val, _ = predict(model, val_loader, device) score = macro_f1(y_val, pred_val) print(f"epoch {epoch:2d}/{epochs} validation macro-F1 {100 * score:.2f}") if score > best_score: best_score, best_state = score, copy.deepcopy(model.state_dict()) if keep == "best_val": model.load_state_dict(best_state) return model