学术
模块更新于 2026-11-20· 浏览 1· 下载 0

PPA 并行化补丁感知注意力模块

三分支多尺度:并行的局部(p=2)、全局(p=4)patch 感知注意力分支分抓局部细节与全局上下文,三个串联 3×3 卷积替代 7×7/5×5/3×3 大核,加跳连求和,一次前向拿到多尺度特征

计算机视觉计算机视觉红外小目标检测PPA注意力机制

结构图

PPA 并行化补丁感知注意力模块结构图
PPA 并行化补丁感知注意力模块结构图

三分支多尺度:并行的局部(p=2)、全局(p=4)patch 感知注意力分支分抓局部细节与全局上下文,三个串联 3×3 卷积替代 7×7/5×5/3×3 大核,加跳连求和,一次前向拿到多尺度特征

论文信息

  • 论文:HCF-Net: Hierarchical Context Fusion Network for Infrared Small Object Detection
  • 出处:arXiv 2024

核心痛点

红外小目标往往只占几个像素、热信号弱、轮廓不清,现有网络多次下采样极易丢掉小目标信息;加上红外图像对比度低、背景复杂,普通卷积基础块缺乏多尺度建模与注意力增强,小目标特征被背景淹没。

模块亮点

  • 三分支多尺度:并行的局部(p=2)、全局(p=4)patch 感知注意力分支分抓局部细节与全局上下文,三个串联 3×3 卷积替代 7×7/5×5/3×3 大核,加跳连求和,一次前向拿到多尺度特征
  • 涨点实打实:SIRST 消融中,U-Net 基线基础块换成 PPA 后,IoU 71.2→75.3(+4.1)、nIoU 74.4→76.9;配上 DASI、MDCR 的整体模型达到 IoU 80.09,超过 UIUNet、SwinT 等方法
  • 轻量精炼:patch 划分只用 Unfold/reshape 操作,不做全局自注意力;融合特征再经 ECA 通道注意力和空间注意力精炼,可直接替换普通卷积块

适用场景

领域为红外小目标检测(军事、安防、海上救援等);原文在 SIRST 数据集上验证了 IoU / nIoU;也可迁移到可见光与遥感小目标检测、医学小病灶分割等任务。

插入位置建议

  • 替换 U-Net 类编码器-解码器的基础卷积块,原文编码器就是 PPA 与最大池化交替堆叠,解码器是 PPA 配转置卷积
  • 作为即插即用增强块接在 CNN 骨干每个 stage 卷积组后面,分辨率不变,插上就能跑
  • 放在 FPN、跳跃连接这类同尺度特征融合之前,先经 PPA 做多尺度增强再融合,减少小目标漏检

适用任务

  • 红外小目标检测

完整代码

ppa.py
import math
import torch
import torch.nn as nn
import torch.nn.functional as F


# 24年3月的新型注意力
"""
红外小物体检测是一项重要的计算机视觉任务,涉及红外图像中微小物体的识别和定位,红外图像通常只包含几个像素。然而,由于物体的尺寸很小,而且红外图像的背景通常很复杂,因此它遇到了困难。
在本文中,我们提出了一种深度学习方法,该方法通过多个实用模块显著提高了红外小目标检测性能。具体来说,它包括并行化贴片感知注意力 (PPA) 模块、维度感知选择性集成 (DASI) 模块和多扩张通道细化器 (MDCR) 模块。
PPA 模块使用多分支特征提取策略来捕获不同规模和级别的特征信息。DASI模块支持自适应通道选择和融合。MDCR模块通过多个深度可分离的卷积层捕获不同感受野范围的空间特征。
"""


class SpatialAttentionModule(nn.Module):
    def __init__(self):
        super(SpatialAttentionModule, self).__init__()
        self.conv2d = nn.Conv2d(in_channels=2, out_channels=1, kernel_size=7, stride=1, padding=3)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        avgout = torch.mean(x, dim=1, keepdim=True)
        maxout, _ = torch.max(x, dim=1, keepdim=True)
        out = torch.cat([avgout, maxout], dim=1)
        out = self.sigmoid(self.conv2d(out))
        return out * x

class LocalGlobalAttention(nn.Module):
    def __init__(self, output_dim, patch_size):
        super().__init__()
        self.output_dim = output_dim
        self.patch_size = patch_size
        self.mlp1 = nn.Linear(patch_size*patch_size, output_dim // 2)
        self.norm = nn.LayerNorm(output_dim // 2)
        self.mlp2 = nn.Linear(output_dim // 2, output_dim)
        self.conv = nn.Conv2d(output_dim, output_dim, kernel_size=1)
        self.prompt = torch.nn.parameter.Parameter(torch.randn(output_dim, requires_grad=True))
        self.top_down_transform = torch.nn.parameter.Parameter(torch.eye(output_dim), requires_grad=True)

    def forward(self, x):
        x = x.permute(0, 2, 3, 1)
        B, H, W, C = x.shape
        P = self.patch_size

        # Local branch
        local_patches = x.unfold(1, P, P).unfold(2, P, P)  # (B, H/P, W/P, P, P, C)
        local_patches = local_patches.reshape(B, -1, P*P, C)  # (B, H/P*W/P, P*P, C)
        local_patches = local_patches.mean(dim=-1)  # (B, H/P*W/P, P*P)

        local_patches = self.mlp1(local_patches)  # (B, H/P*W/P, input_dim // 2)
        local_patches = self.norm(local_patches)  # (B, H/P*W/P, input_dim // 2)
        local_patches = self.mlp2(local_patches)  # (B, H/P*W/P, output_dim)

        local_attention = F.softmax(local_patches, dim=-1)  # (B, H/P*W/P, output_dim)
        local_out = local_patches * local_attention # (B, H/P*W/P, output_dim)

        cos_sim = F.normalize(local_out, dim=-1) @ F.normalize(self.prompt[None, ..., None], dim=1)  # B, N, 1
        mask = cos_sim.clamp(0, 1)
        local_out = local_out * mask
        local_out = local_out @ self.top_down_transform

        # Restore shapes
        local_out = local_out.reshape(B, H // P, W // P, self.output_dim)  # (B, H/P, W/P, output_dim)
        local_out = local_out.permute(0, 3, 1, 2)
        local_out = F.interpolate(local_out, size=(H, W), mode='bilinear', align_corners=False)
        output = self.conv(local_out)

        return output


class ECA(nn.Module):
    def __init__(self,in_channel,gamma=2,b=1):
        super(ECA, self).__init__()
        k=int(abs((math.log(in_channel,2)+b)/gamma))
        kernel_size=k if k % 2 else k+1
        padding=kernel_size//2
        self.pool=nn.AdaptiveAvgPool2d(output_size=1)
        self.conv=nn.Sequential(
            nn.Conv1d(in_channels=1,out_channels=1,kernel_size=kernel_size,padding=padding,bias=False),
            nn.Sigmoid()
        )

    def forward(self,x):
        out=self.pool(x)
        out=out.view(x.size(0),1,x.size(1))
        out=self.conv(out)
        out=out.view(x.size(0),x.size(1),1,1)
        return out*x


class conv_block(nn.Module):
    def __init__(self,
                 in_features,
                 out_features,
                 kernel_size=(3, 3),
                 stride=(1, 1),
                 padding=(1, 1),
                 dilation=(1, 1),
                 norm_type='bn',
                 activation=True,
                 use_bias=True,
                 groups = 1
                 ):
        super().__init__()
        self.conv = nn.Conv2d(in_channels=in_features,
                              out_channels=out_features,
                              kernel_size=kernel_size,
                              stride=stride,
                              padding=padding,
                              dilation=dilation,
                              bias=use_bias,
                              groups = groups)

        self.norm_type = norm_type
        self.act = activation

        if self.norm_type == 'gn':
            self.norm = nn.GroupNorm(32 if out_features >= 32 else out_features, out_features)
        if self.norm_type == 'bn':
            self.norm = nn.BatchNorm2d(out_features)
        if self.act:
            # self.relu = nn.GELU()
            self.relu = nn.ReLU(inplace=False)


    def forward(self, x):
        x = self.conv(x)
        if self.norm_type is not None:
            x = self.norm(x)
        if self.act:
            x = self.relu(x)
        return x

class PPA(nn.Module):
    def __init__(self, in_features, filters) -> None:
         super().__init__()

         self.skip = conv_block(in_features=in_features,
                                out_features=filters,
                                kernel_size=(1, 1),
                                padding=(0, 0),
                                norm_type='bn',
                                activation=False)
         self.c1 = conv_block(in_features=in_features,
                                out_features=filters,
                                kernel_size=(3, 3),
                                padding=(1, 1),
                                norm_type='bn',
                                activation=True)
         self.c2 = conv_block(in_features=filters,
                                out_features=filters,
                                kernel_size=(3, 3),
                                padding=(1, 1),
                                norm_type='bn',
                                activation=True)
         self.c3 = conv_block(in_features=filters,
                                out_features=filters,
                                kernel_size=(3, 3),
                                padding=(1, 1),
                                norm_type='bn',
                                activation=True)
         self.sa = SpatialAttentionModule()
         self.cn = ECA(filters)
         self.lga2 = LocalGlobalAttention(filters, 2)
         self.lga4 = LocalGlobalAttention(filters, 4)

         self.bn1 = nn.BatchNorm2d(filters)
         self.drop = nn.Dropout2d(0.1)
         self.relu = nn.ReLU()

         self.gelu = nn.GELU()

    def forward(self, x):
        x_skip = self.skip(x)
        x_lga2 = self.lga2(x_skip)
        x_lga4 = self.lga4(x_skip)
        x1 = self.c1(x)
        x2 = self.c2(x1)
        x3 = self.c3(x2)
        x = x1 + x2 + x3 + x_skip + x_lga2 + x_lga4
        x = self.cn(x)
        x = self.sa(x)
        x = self.drop(x)
        x = self.bn1(x)
        x = self.relu(x)
        return x


if __name__ == '__main__':
    block = PPA(in_features=3, filters=3)
    input = torch.rand(32, 3, 224, 224)
    output = block(input)
    print('Input size:', input.size())
    print('Output size:', output.size())

环境与依赖

Python 3.9+

继续浏览

下一篇PConv 风车形卷积卷积核转成风车:四路不对称 padding 配 1×k、k×1 卷积向外发散,拼接融合后感受野由中心向外递减、形似高斯分布,天然贴合红外小目标特性

相关资源