1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| class YOLOv12Nano(nn.Module): """ YOLOv12-N 架构概要 核心特点: 1. CNN骨干 + 注意力机制 2. 使用传统YOLO管道 (需NMS后处理) 3. 中等速度+精度 优势: 注意力提升特征建模 劣势: NMS增加后处理延迟 """ def __init__(self, num_classes=80): super().__init__() self.backbone = nn.Sequential( self._conv_block(3, 24, 3, 2), self._conv_block(24, 48, 3, 2), self._conv_block(48, 96, 3, 2), self._conv_block(96, 192, 3, 2), ) self.attention = A2Attention(192) self.head = nn.Sequential( nn.Conv2d(192, 128, 1), nn.Conv2d(128, num_classes + 5, 1) ) def _conv_block(self, in_ch, out_ch, k, s): return nn.Sequential( nn.Conv2d(in_ch, out_ch, k, s, k//2, bias=False), nn.BatchNorm2d(out_ch), nn.SiLU(inplace=True) ) def forward(self, x): features = self.backbone(x) features = self.attention(features) outputs = self.head(features) return outputs
class A2Attention(nn.Module): """A²注意力: 凸组合替代传统自注意力""" def __init__(self, channels): super().__init__() self.conv1 = nn.Conv2d(channels, channels//4, 1) self.conv2 = nn.Conv2d(channels, channels//4, 1) self.conv3 = nn.Conv2d(channels, channels//4, 1) def forward(self, x): b, c, h, w = x.shape a = torch.softmax(self.conv1(x).flatten(2), dim=-1) d = torch.softmax(self.conv2(x).flatten(2), dim=1) g = self.conv3(x).flatten(2) out = torch.matmul(g, a) @ d return x + out.reshape(b, c//4, h, w)
|