class ConvNeXt(d2l.Classifier):
def __init__(self, arch=((2, 40), (2, 80), (6, 160), (2, 320)),
lr=2e-3, num_classes=10, drop_path_max=0.1,
norm=LayerNorm2d):
super().__init__()
self.save_hyperparameters()
depths = [d for d, c in arch]
rates = torch.linspace(0, drop_path_max, sum(depths)).tolist()
layers = self.stem(arch[0][1], norm)
c_prev, b = arch[0][1], 0
for i, (depth, c) in enumerate(arch):
if i > 0: # Separate downsampling layer between stages
layers += [norm(c_prev),
nn.Conv2d(c_prev, c, kernel_size=2, stride=2)]
for _ in range(depth):
layers.append(ConvNeXtBlock(c, rates[b], norm=norm))
b += 1
c_prev = c
layers += [nn.AdaptiveAvgPool2d((1, 1)), norm(c_prev), nn.Flatten(),
nn.Linear(c_prev, num_classes)]
self.net = nn.Sequential(*layers)
self.net.apply(self.weight_init)
def stem(self, c, norm): # Patchify: a 4x4 convolution with stride 4
return [nn.Conv2d(1, c, kernel_size=4, stride=4), norm(c)]
def weight_init(self, module):
if type(module) in (nn.Conv2d, nn.Linear):
nn.init.normal_(module.weight, std=0.02)
nn.init.zeros_(module.bias)