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

ODCNOV ODConv 全维度动态卷积

原理创新:提出并行多维注意力机制,同时对卷积核的空间、输入通道、输出通道、核数量四个维度生成互补注意力,逐维度加权卷积核,大幅提升特征提取能力。

计算机视觉计算机视觉动态卷积注意力机制ICLRYOLO目标检测图像分类算法优化

结构图

ODCNOV ODConv 全维度动态卷积结构图
ODCNOV ODConv 全维度动态卷积结构图

原理创新:提出并行多维注意力机制,同时对卷积核的空间、输入通道、输出通道、核数量四个维度生成互补注意力,逐维度加权卷积核,大幅提升特征提取能力。

核心痛点

传统动态卷积(CondConv、DyConv)仅在卷积核数量维度施加输入自适应注意力,完全忽略卷积核的空间尺寸、输入通道、输出通道三个维度的建模,特征提取能力受限;同时依赖多卷积核堆叠提升性能,参数量暴涨,在大尺寸CNN上涨点效果极差。

模块亮点

  • 原理创新:提出并行多维注意力机制,同时对卷积核的空间、输入通道、输出通道、核数量四个维度生成互补注意力,逐维度加权卷积核,大幅提升特征提取能力。
  • 性能增益显著:ImageNet分类任务上,MobileNetV2系列最高涨5.71% top-1精度,ResNet系列最高涨3.72% top-1精度;下游COCO检测任务上,最高提升2.0% AP,优于SE、CBAM等主流注意力模块。
  • 效率友好:单卷积核版本ODConv性能即可超过8核CondConv、4核DyConv,额外参数量降低70%以上,推理速度损失极小,兼顾精度与部署效率。

适用场景

适用于全CV领域,可嵌入ResNet、MobileNet、YOLO系列等所有基于卷积的CNN架构,解决图像分类、目标检测、语义分割等任务的涨点需求,尤其适配轻量化模型部署场景。

插入位置建议

  • 作为普通卷积的即插即用替换,直接替换backbone中除第一层输入卷积外的所有普通卷积即可;若要进一步降低开销,可仅替换残差块/瓶颈结构中的3×3卷积。

适用任务

  • 全CV领域
  • 可嵌入ResNet
  • MobileNet

完整代码

odcnov.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.autograd


"""
在每个卷积层中学习单个静态卷积核是现代卷积神经网络 (CNN) 的常见训练范式相反.
最近在动态卷积方面的研究表明,学习用输入相关注意力加权的卷积核可以显著提高轻量级 CNN 的准确性,同时保持高效的推理。
然而,我们观察到,现有的工作通过核空间的一个维度(关于卷积核数)赋予卷积核动态属性,而忽略了其他三个维度(关于空间大小、输入通道数和每个卷积核的输出通道数)。
受此启发,我们提出了全维动态卷积(ODConv),这是一种更通用但更优雅的动态卷积设计,以推进这一研究方向。
ODConv 利用一种具有并行策略的新型多维注意力机制,在任何卷积层沿核空间的所有四个维度学习卷积核的互补注意力。

作为常规卷积的直接替代品,ODConv 可以插入到许多 CNN 架构中。

在ImageNet和MS-COCO数据集上的大量实验表明,ODConv为各种流行的CNN骨干网(包括轻量级和大型主干网)带来了坚实的精度提升,
例如,MobivleNetV2|ImageNet 数据集上的 ResNet 系列。
有趣的是,由于其改进的特征学习能力,即使具有单个内核的 ODConv 也可以与具有多个内核的现有动态卷积对应物竞争或优于现有动态卷积对应物,从而大大减少了额外的参数。
此外,ODConv 在调制输出特征或卷积权重方面也优于其他注意力模块。
"""


class Attention(nn.Module):
    def __init__(self, in_planes, out_planes, kernel_size, groups=1, reduction=0.0625, kernel_num=4, min_channel=16):
        super(Attention, self).__init__()
        attention_channel = max(int(in_planes * reduction), min_channel)
        self.kernel_size = kernel_size
        self.kernel_num = kernel_num
        self.temperature = 1.0

        self.avgpool = nn.AdaptiveAvgPool2d(1)
        self.fc = nn.Conv2d(in_planes, attention_channel, 1, bias=False)
        self.bn = nn.BatchNorm2d(attention_channel)
        self.relu = nn.ReLU(inplace=True)

        self.channel_fc = nn.Conv2d(attention_channel, in_planes, 1, bias=True)
        self.func_channel = self.get_channel_attention

        if in_planes == groups and in_planes == out_planes:  # depth-wise convolution
            self.func_filter = self.skip
        else:
            self.filter_fc = nn.Conv2d(attention_channel, out_planes, 1, bias=True)
            self.func_filter = self.get_filter_attention

        if kernel_size == 1:  # point-wise convolution
            self.func_spatial = self.skip
        else:
            self.spatial_fc = nn.Conv2d(attention_channel, kernel_size * kernel_size, 1, bias=True)
            self.func_spatial = self.get_spatial_attention

        if kernel_num == 1:
            self.func_kernel = self.skip
        else:
            self.kernel_fc = nn.Conv2d(attention_channel, kernel_num, 1, bias=True)
            self.func_kernel = self.get_kernel_attention

        self._initialize_weights()

    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
            if isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def update_temperature(self, temperature):
        self.temperature = temperature

    @staticmethod
    def skip(_):
        return 1.0

    def get_channel_attention(self, x):
        channel_attention = torch.sigmoid(self.channel_fc(x).view(x.size(0), -1, 1, 1) / self.temperature)
        return channel_attention

    def get_filter_attention(self, x):
        filter_attention = torch.sigmoid(self.filter_fc(x).view(x.size(0), -1, 1, 1) / self.temperature)
        return filter_attention

    def get_spatial_attention(self, x):
        spatial_attention = self.spatial_fc(x).view(x.size(0), 1, 1, 1, self.kernel_size, self.kernel_size)
        spatial_attention = torch.sigmoid(spatial_attention / self.temperature)
        return spatial_attention

    def get_kernel_attention(self, x):
        kernel_attention = self.kernel_fc(x).view(x.size(0), -1, 1, 1, 1, 1)
        kernel_attention = F.softmax(kernel_attention / self.temperature, dim=1)
        return kernel_attention

    def forward(self, x):
        x = self.avgpool(x)
        x = self.fc(x)
        x = self.bn(x)
        x = self.relu(x)
        return self.func_channel(x), self.func_filter(x), self.func_spatial(x), self.func_kernel(x)


class ODConv2d(nn.Module):
    def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=1, dilation=1, groups=1,
                 reduction=0.0625, kernel_num=4):
        super(ODConv2d, self).__init__()
        self.in_planes = in_planes
        self.out_planes = out_planes
        self.kernel_size = kernel_size
        self.stride = stride
        self.padding = padding
        self.dilation = dilation
        self.groups = groups
        self.kernel_num = kernel_num
        self.attention = Attention(in_planes, out_planes, kernel_size, groups=groups,
                                   reduction=reduction, kernel_num=kernel_num)
        self.weight = nn.Parameter(torch.randn(kernel_num, out_planes, in_planes//groups, kernel_size, kernel_size),
                                   requires_grad=True)
        self._initialize_weights()

        if self.kernel_size == 1 and self.kernel_num == 1:
            self._forward_impl = self._forward_impl_pw1x
        else:
            self._forward_impl = self._forward_impl_common

    def _initialize_weights(self):
        for i in range(self.kernel_num):
            nn.init.kaiming_normal_(self.weight[i], mode='fan_out', nonlinearity='relu')

    def update_temperature(self, temperature):
        self.attention.update_temperature(temperature)

    def _forward_impl_common(self, x):
        # Multiplying channel attention (or filter attention) to weights and feature maps are equivalent,
        # while we observe that when using the latter method the models will run faster with less gpu memory cost.
        channel_attention, filter_attention, spatial_attention, kernel_attention = self.attention(x)
        batch_size, in_planes, height, width = x.size()
        x = x * channel_attention
        x = x.reshape(1, -1, height, width)
        aggregate_weight = spatial_attention * kernel_attention * self.weight.unsqueeze(dim=0)
        aggregate_weight = torch.sum(aggregate_weight, dim=1).view(
            [-1, self.in_planes // self.groups, self.kernel_size, self.kernel_size])
        output = F.conv2d(x, weight=aggregate_weight, bias=None, stride=self.stride, padding=self.padding,
                          dilation=self.dilation, groups=self.groups * batch_size)
        output = output.view(batch_size, self.out_planes, output.size(-2), output.size(-1))
        output = output * filter_attention
        return output

    def _forward_impl_pw1x(self, x):
        channel_attention, filter_attention, spatial_attention, kernel_attention = self.attention(x)
        x = x * channel_attention
        output = F.conv2d(x, weight=self.weight.squeeze(dim=0), bias=None, stride=self.stride, padding=self.padding,
                          dilation=self.dilation, groups=self.groups)
        output = output * filter_attention
        return output

    def forward(self, x):
        return self._forward_impl(x)


if __name__ == '__main__':
    block = ODConv2d(in_planes=3, out_planes=3, kernel_size=3)
    input = torch.rand(16, 3, 32, 32)
    output = block(input)
    print('Input size:', input.size())
    print('Output size:', output.size())

环境与依赖

Python 3.9+

继续浏览

下一篇PiCoKV 二值码KV注意力将解码矩阵折入查询侧和词元归约之后,让键打分与值聚合都在二值码上进行位运算。密集和全局分支共享归一化;所附源码是算子示范,并非专用高速内核。

相关资源