duyle2408's picture
Upload 21 files
a490ef3 verified
Raw
History Blame Contribute Delete
4.53 kB
import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvBNAct(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, groups=1, act=True):
super().__init__()
padding = kernel_size // 2
self.block = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, groups=groups, bias=False),
nn.BatchNorm2d(out_channels),
nn.SiLU(inplace=True) if act else nn.Identity(),
)
def forward(self, x):
return self.block(x)
class SimpleFPN(nn.Module):
"""Top-down FPN for features ordered high-resolution to low-resolution."""
def __init__(self, in_channels, out_channels=128):
super().__init__()
self.lateral = nn.ModuleList([ConvBNAct(c, out_channels, kernel_size=1) for c in in_channels])
self.output = nn.ModuleList([ConvBNAct(out_channels, out_channels, kernel_size=3) for _ in in_channels])
def forward(self, features):
laterals = [layer(feature) for layer, feature in zip(self.lateral, features)]
for idx in range(len(laterals) - 1, 0, -1):
up = F.interpolate(laterals[idx], size=laterals[idx - 1].shape[-2:], mode="nearest")
laterals[idx - 1] = laterals[idx - 1] + up
return [layer(feature) for layer, feature in zip(self.output, laterals)]
class BottleneckLite(nn.Module):
def __init__(self, channels, shortcut=True):
super().__init__()
hidden = max(8, channels // 2)
self.shortcut = shortcut
self.cv1 = ConvBNAct(channels, hidden, kernel_size=1)
self.cv2 = ConvBNAct(hidden, channels, kernel_size=3)
def forward(self, x):
y = self.cv2(self.cv1(x))
return x + y if self.shortcut else y
class C2fLite(nn.Module):
"""Small YOLO-style concat block for neck fusion."""
def __init__(self, in_channels, out_channels, num_blocks=2):
super().__init__()
hidden = max(8, out_channels // 2)
self.reduce = ConvBNAct(in_channels, hidden * 2, kernel_size=1)
self.blocks = nn.ModuleList([BottleneckLite(hidden, shortcut=True) for _ in range(num_blocks)])
self.fuse = ConvBNAct(hidden * (2 + num_blocks), out_channels, kernel_size=1)
def forward(self, x):
y = list(self.reduce(x).chunk(2, dim=1))
for block in self.blocks:
y.append(block(y[-1]))
return self.fuse(torch.cat(y, dim=1))
class YOLOPANNeck(nn.Module):
"""PAN-FPN style neck: upsample/concat top-down, then downsample/concat bottom-up."""
def __init__(self, in_channels, out_channels=128, num_blocks=2):
super().__init__()
c3, c4, c5 = in_channels
self.p3_lateral = ConvBNAct(c3, out_channels, kernel_size=1)
self.p4_lateral = ConvBNAct(c4, out_channels, kernel_size=1)
self.p5_lateral = ConvBNAct(c5, out_channels, kernel_size=1)
self.top_p4 = C2fLite(out_channels * 2, out_channels, num_blocks=num_blocks)
self.top_p3 = C2fLite(out_channels * 2, out_channels, num_blocks=num_blocks)
self.down_p3 = ConvBNAct(out_channels, out_channels, kernel_size=3, stride=2)
self.bottom_p4 = C2fLite(out_channels * 2, out_channels, num_blocks=num_blocks)
self.down_p4 = ConvBNAct(out_channels, out_channels, kernel_size=3, stride=2)
self.bottom_p5 = C2fLite(out_channels * 2, out_channels, num_blocks=num_blocks)
def forward(self, features):
p3, p4, p5 = features
p3 = self.p3_lateral(p3)
p4 = self.p4_lateral(p4)
p5 = self.p5_lateral(p5)
p4_td = self.top_p4(torch.cat([F.interpolate(p5, size=p4.shape[-2:], mode="nearest"), p4], dim=1))
p3_out = self.top_p3(torch.cat([F.interpolate(p4_td, size=p3.shape[-2:], mode="nearest"), p3], dim=1))
p4_out = self.bottom_p4(torch.cat([self.down_p3(p3_out), p4_td], dim=1))
p5_out = self.bottom_p5(torch.cat([self.down_p4(p4_out), p5], dim=1))
return [p3_out, p4_out, p5_out]
def make_locations(feature_shapes, strides, device):
locations = []
for (height, width), stride in zip(feature_shapes, strides):
shifts_x = (torch.arange(width, device=device, dtype=torch.float32) + 0.5) * stride
shifts_y = (torch.arange(height, device=device, dtype=torch.float32) + 0.5) * stride
grid_y, grid_x = torch.meshgrid(shifts_y, shifts_x, indexing="ij")
locations.append(torch.stack((grid_x.reshape(-1), grid_y.reshape(-1)), dim=1))
return locations