class ClassicRecipe(ResNet18):
"""Recipe A: SGD with momentum, weight decay, warmup, step decay."""
def configure_optimizers(self):
optim = torch.optim.SGD(self.parameters(), lr=self.lr, momentum=0.9,
weight_decay=5e-4)
warmup = 2 * self.num_steps // 30 # Two of the 30 epochs
return optim, torch.optim.lr_scheduler.LambdaLR(
optim, lambda t: step_decay(t, self.num_steps, warmup))
class ModernRecipe(ResNet18):
"""Compact modern recipe: AdamW, warmup and cosine, smoothing, Mixup."""
def configure_optimizers(self):
warmup = 3 * self.num_steps // 45 # Three of the 45 epochs
optim = torch.optim.AdamW(self.parameters(), lr=self.lr,
weight_decay=0.05)
return optim, torch.optim.lr_scheduler.LambdaLR(
optim, lambda t: d2l.cosine_warmup(t, self.num_steps, warmup))
def training_step(self, batch):
X, y_a, y_b, lam = mixup(*batch, alpha=0.2)
Y_hat = self(X)
smooth = lambda y: F.cross_entropy(Y_hat, y, label_smoothing=0.1)
return lam * smooth(y_a) + (1 - lam) * smooth(y_b)