# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in this directory. It is adapted (vendored, self-contained) # from facebookresearch/ConvNeXt-V2 (models/convnextv2.py, models/utils.py): # the timm and MinkowskiEngine dependencies are removed and the sparse # (FCMAE pretraining) code paths dropped, so only the dense inference model # remains. The architecture and parameter names are unchanged, so checkpoints # trained with the upstream code load without modification. import torch import torch.nn as nn import torch.nn.functional as F def trunc_normal_(tensor, std=0.02): # No-op at inference: weights are loaded from a checkpoint, so the # init distribution is irrelevant. Kept only so _init_weights runs. return tensor class LayerNorm(nn.Module): """LayerNorm supporting channels_last (N, H, W, C) or channels_first (N, C, H, W) layouts.""" def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"): super().__init__() self.weight = nn.Parameter(torch.ones(normalized_shape)) self.bias = nn.Parameter(torch.zeros(normalized_shape)) self.eps = eps self.data_format = data_format if self.data_format not in ["channels_last", "channels_first"]: raise NotImplementedError self.normalized_shape = (normalized_shape,) def forward(self, x): if self.data_format == "channels_last": return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps) u = x.mean(1, keepdim=True) s = (x - u).pow(2).mean(1, keepdim=True) x = (x - u) / torch.sqrt(s + self.eps) return self.weight[:, None, None] * x + self.bias[:, None, None] class GRN(nn.Module): """Global Response Normalization.""" def __init__(self, dim): super().__init__() self.gamma = nn.Parameter(torch.zeros(1, 1, 1, dim)) self.beta = nn.Parameter(torch.zeros(1, 1, 1, dim)) def forward(self, x): Gx = torch.norm(x, p=2, dim=(1, 2), keepdim=True) Nx = Gx / (Gx.mean(dim=-1, keepdim=True) + 1e-6) return self.gamma * (x * Nx) + self.beta + x class Block(nn.Module): """ConvNeXt V2 block. drop_path is unused at inference (always Identity).""" def __init__(self, dim, drop_path=0.0): super().__init__() self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim) self.norm = LayerNorm(dim, eps=1e-6) self.pwconv1 = nn.Linear(dim, 4 * dim) self.act = nn.GELU() self.grn = GRN(4 * dim) self.pwconv2 = nn.Linear(4 * dim, dim) self.drop_path = nn.Identity() def forward(self, x): inp = x x = self.dwconv(x) x = x.permute(0, 2, 3, 1) x = self.norm(x) x = self.pwconv1(x) x = self.act(x) x = self.grn(x) x = self.pwconv2(x) x = x.permute(0, 3, 1, 2) return inp + self.drop_path(x) class ConvNeXtV2(nn.Module): def __init__(self, in_chans=3, num_classes=1000, depths=(3, 3, 9, 3), dims=(96, 192, 384, 768), drop_path_rate=0.0, head_init_scale=1.0): super().__init__() self.depths = depths self.downsample_layers = nn.ModuleList() stem = nn.Sequential( nn.Conv2d(in_chans, dims[0], kernel_size=4, stride=4), LayerNorm(dims[0], eps=1e-6, data_format="channels_first"), ) self.downsample_layers.append(stem) for i in range(3): self.downsample_layers.append(nn.Sequential( LayerNorm(dims[i], eps=1e-6, data_format="channels_first"), nn.Conv2d(dims[i], dims[i + 1], kernel_size=2, stride=2), )) self.stages = nn.ModuleList() dp_rates = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] cur = 0 for i in range(4): self.stages.append(nn.Sequential( *[Block(dim=dims[i], drop_path=dp_rates[cur + j]) for j in range(depths[i])] )) cur += depths[i] self.norm = nn.LayerNorm(dims[-1], eps=1e-6) self.head = nn.Linear(dims[-1], num_classes) self.apply(self._init_weights) self.head.weight.data.mul_(head_init_scale) self.head.bias.data.mul_(head_init_scale) def _init_weights(self, m): if isinstance(m, (nn.Conv2d, nn.Linear)): trunc_normal_(m.weight, std=0.02) if m.bias is not None: nn.init.constant_(m.bias, 0) def forward_features(self, x): for i in range(4): x = self.downsample_layers[i](x) x = self.stages[i](x) return self.norm(x.mean([-2, -1])) def forward(self, x): return self.head(self.forward_features(x)) def convnextv2_nano(**kwargs): return ConvNeXtV2(depths=[2, 2, 8, 2], dims=[80, 160, 320, 640], **kwargs) def convnextv2_tiny(**kwargs): return ConvNeXtV2(depths=[3, 3, 9, 3], dims=[96, 192, 384, 768], **kwargs) def convnextv2_base(**kwargs): return ConvNeXtV2(depths=[3, 3, 27, 3], dims=[128, 256, 512, 1024], **kwargs) FACTORY = { "cv2n": convnextv2_nano, "cv2t": convnextv2_tiny, "cv2b": convnextv2_base, }