前言

本文介绍了一种高效视觉注意力机制——Circulant Attention,用于缓解标准自注意力在高分辨率特征建模中的二次复杂度问题。该方法将注意力矩阵建模为近似 BCCB 的结构化循环矩阵,并借助二维傅里叶变换实现快速相关计算与特征聚合,在保留全局建模能力的同时将复杂度降至 O(NlogN)。我们将 Circulant Attention 成功集成进 YOLO26 的 C2PSA 模块,替代原有注意力计算方式,使网络在高分辨率目标检测场景中获得更高效的上下文建模能力。

文章目录: YOLO26改进大全:卷积层、轻量化、注意力机制、损失函数、Backbone、SPPF、Neck、检测头全方位优化汇总
专栏链接: 最新YOLO26改进专栏

介绍

image-20260814154058080

自注意力机制一直是视觉 Transformer 发展的关键因素,但其二次复杂度在高分辨率场景中带来了沉重的计算负担,限制了实际应用。已有方法通常通过引入局部性、稀疏性等人工设计模式来缓解这一问题,但这些约束往往会削弱模型容量。本文提出一种新的注意力范式 Circulant Attention,通过挖掘自注意力内部天然存在的高效结构来提升效率。作者首先发现,视觉 Transformer 中的自注意力矩阵常常近似于带循环块的块循环矩阵,即 BCCB。此类结构化矩阵与其他矩阵相乘时可以通过离散傅里叶变换在 O(NlogN) 时间内完成。基于这一观察,作者将注意力图显式建模为其最近的 BCCB 矩阵,并提出高效计算算法。该方法整体形式与标准自注意力非常接近,主要区别在于使用 BCCB 注意力矩阵。由于该设计来自自注意力本身学习到的高效模式,它既能将计算复杂度降至 O(NlogN),又能较好保持标准自注意力的表达能力。大量视觉任务实验表明,该方法有效且高效,可作为视觉 Transformer 架构中自注意力的有前景替代方案。

文章链接

论文地址:论文地址

代码地址:代码地址

基本原理

1. 解决的关键问题

Circulant Attention 主要针对视觉 Transformer 在高分辨率图像建模中的计算瓶颈。标准 self-attention 会计算所有 token 两两之间的相似度,若图像特征图包含 N 个 token,注意力矩阵大小就是 N×N,计算复杂度约为 O(N²)。这在 ImageNet 224×224 分类场景中还能承受,但一旦进入目标检测、实例分割、语义分割等高分辨率密集预测任务,N 会迅速增大,全局注意力的计算和显存成本都会变得昂贵。

以往高效 ViT 常用局部窗口、稀疏采样、下采样 K/V 等方式减少计算,例如 Swin 的窗口注意力、PVT 的空间降采样注意力。这些方法确实降低了复杂度,但本质上是在自注意力之外人为规定注意力模式,可能牺牲全局建模能力。本文的切入点更有意思:作者观察 DeiT 等视觉 Transformer 的实际注意力图后发现,即使没有人工限制,视觉自注意力也经常学出接近 BCCB 的结构。BCCB 是二维场景下循环矩阵的推广,其矩阵乘法可等价为二维循环互相关,并能通过 2D DFT/FFT 高效计算。因此,论文不是简单裁剪注意力范围,而是把自注意力已经倾向学习的结构显式化,用结构化矩阵替代稠密注意力矩阵,在保持全局感受野的同时把复杂度从 O(N²) 降到 O(NlogN)。

2. 整体架构

Circulant Attention 被设计成一个 plug-in attention module,可以替换不同视觉 Transformer 中原有的注意力模块。论文将它应用到三类代表性架构:DeiT、PVT 和 Swin Transformer,分别对应全局自注意力、稀疏注意力和局部窗口注意力。替换后得到 CA-DeiT、CA-PVT、CA-Swin,并进一步构建了专门的 Circulant Attention Transformer,即 CAT 系列模型。

从模块位置看,它仍然接收标准注意力中的 Q、K、V 输入,也保留“由 Q/K 产生注意力权重,再聚合 V”的基本流程。不同之处在于,标准 self-attention 先计算 A=QKᵀ/√d,再对 A 做 Softmax 并乘以 V;Circulant Attention 则把原始注意力图 A 投影到 BCCB 矩阵子空间,得到最近的结构化注意力矩阵 Ã。由于 BCCB 矩阵可由第一行完全确定,模块不需要显式构造完整 N×N 注意力图,而是计算其第一行表示,再利用 DFT-based multiplication 完成注意力聚合。

论文还加入了 token reweighting module。原因是 BCCB 结构经 Softmax 后会同时约束行和列的归一化,使不同 key 被聚合的总权重趋于均衡,削弱模型突出关键 token 的能力。为补足这一点,作者引入输入相关的重加权因子 T=SiLU(xW_T),并比较了 pre-reweighting 与 post-reweighting 两种形式。最终默认采用 post-reweighting,即先执行 CirAttn(Q,K,V),再用 T 对输出 token 进行重加权。

3. 技术原理

Circulant Attention 的核心数学对象是 BCCB,即 Block Circulant matrix with Circulant Blocks。普通循环矩阵的特点是每一行都是上一行的循环位移,矩阵乘向量可视为一维循环互相关,因此能用 1D DFT 加速。BCCB 则把这一性质推广到二维特征图:当 N=H×W 时,N×N 的 BCCB 矩阵可视为 H×H 个块,每个块是 W×W 的循环矩阵,块之间也满足循环结构。这样的矩阵乘法等价于二维循环互相关,也就是深度学习中带 circular padding 的二维全局卷积形式,可通过 2D DFT、Hadamard product 和逆 DFT 计算。

具体到注意力,论文把标准注意力矩阵 A=QKᵀ/√d 投影到 BCCB 子空间,得到 Ã。由于 BCCB 矩阵由第一行 a 决定,作者推导出 a 可以由二维形态的 Q 和 K 进行循环互相关得到。换句话说,注意力分数不再通过显式 N×N 矩阵乘法获得,而是通过 Q 与 K 的 DFT-based correlation 计算。随后对 a 做 Softmax,得到结构化注意力矩阵的第一行 σ(a)。在聚合 V 时,也不构造完整 σ(Ã),而是利用 σ(a) 与 V 的 DFT-based multiplication 完成输出 O=σ(a)⊛V。

这个过程在形式上仍然贴近 self-attention:输入是 Q/K/V,输出是加权后的特征;但内部把“稠密注意力矩阵乘法”换成了“BCCB 结构 + 2D DFT 快速乘法”。论文给出的复杂度分析显示,Circulant Attention 的整体复杂度约为 N(log₂N)(4d+2)+4Nd,而标准 self-attention 约为 2N²d,因此在高分辨率场景下优势会更明显。

实验也支持这一点。ImageNet-1K 上,CA-DeiT、CA-PVT、CA-Swin 相比对应基线普遍提升;例如 CA-PVT-S 能以更少参数和 FLOPs 接近或超过更大的 PVT-L。COCO 检测和 ADE20K 语义分割中,Circulant Attention 的收益更明显,因为这些任务更依赖高分辨率特征图和全局上下文。论文还报告在 1536² 分辨率下,CA-DeiT-T 相比 self-attention 可显著降低 FLOPs,并带来约 7× 的推理加速。整体来看,Circulant Attention 的价值在于:它不是把注意力粗暴局部化,而是利用视觉自注意力中天然出现的近 BCCB 模式,将全局建模改写成可由 FFT 加速的结构化计算,从而在效率和表达能力之间取得更好的平衡。

核心代码

class CirculantAttention(nn.Module):
    r""" Circulant Attention
    https://arxiv.org/abs/2512.21542
    """
    def __init__(self, dim, proj_drop=0.):
        super().__init__()
        self.qkv = Linear(dim, dim * 3)
        self.gate = nn.Sequential(nn.Linear(dim, dim), nn.SiLU())
        self.proj = nn.Linear(dim, dim)
        self.proj_drop = nn.Dropout(proj_drop)

    def forward(self, x):
        b, n, c = x.shape
        h = w = int(n ** 0.5)

        # Prepare Q, K, V, T
        #    (1) qkv=fc(x), qkv=fft(qkv) is mathematically equivalent to x=fft(x), qkv=fc(x)
        #    (2) The latter requires fewer FFT computations, delivering higher throughput
        t = self.gate(x)
        x = x.reshape(b, h, w, c)
        x = torch.fft.rfft2(x, dim=(1, 2), norm='ortho')
        qkv = self.qkv(x)
        q, k, v = torch.chunk(qkv, chunks=3, dim=-1)

        # Equation 15 of the paper
        #    (1) We use d=1 in practice, as discussed in Table 5
        #    (2) The 1/N factor is implicitly achieved by norm='ortho' in calculating Q, K
        attn = torch.conj(q) * k
        attn = torch.fft.irfft2(attn, s=(h, w), dim=(1, 2), norm='ortho')

        # Equation 16 of the paper
        attn = attn.reshape(b, n, c).softmax(dim=1).reshape(b, h, w, c)
        attn = torch.fft.rfft2(attn, dim=(1, 2))
        x = torch.conj(attn) * v
        x = torch.fft.irfft2(x, s=(h, w), dim=(1, 2), norm='ortho')

        # Output
        x = x.reshape(b, n, c) * t
        x = self.proj(x)
        return x

YOLO26引入代码

在根目录下的ultralytics/nn/目录,新建一个 C2PSA目录,然后新建一个以 C2PSA_CirculantAtt 为文件名的py文件, 把代码拷贝进去。

import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from ultralytics.nn.modules.conv import RepConv, Conv
from ultralytics.nn.modules.block import PSABlock, C2PSA

class Linear(nn.Linear):
    r""" Linear layer for complex number inputs.
    """
    def __init__(self, in_features, out_features, device=None, dtype=None):
        super(Linear, self).__init__(in_features, out_features, False, device, dtype)

    def forward(self, x):
        x = torch.view_as_real(x).transpose(-2, -1)
        weight = self.weight if self.weight.dtype == x.dtype else self.weight.to(x.dtype)
        x = torch.nn.functional.linear(x, weight).transpose(-2, -1)
        if x.dtype != torch.float32:
            x = x.to(torch.float32)
        x = torch.view_as_complex(x.contiguous())
        return x

class CirculantAttention(nn.Module):
    r""" Circulant Attention
    https://arxiv.org/abs/2512.21542
    """
    def __init__(self, dim, proj_drop=0.):
        super().__init__()
        self.qkv = Linear(dim, dim * 3)
        self.gate = nn.Sequential(nn.Conv2d(dim, dim, 1), nn.SiLU())
        self.proj = nn.Conv2d(dim, dim, 1)
        self.proj_drop = nn.Dropout(proj_drop)

    def forward(self, x):
        b, c, h, w = x.size()
        n = h * w
        orig_dtype = x.dtype

        # Prepare Q, K, V, T
        #    (1) qkv=fc(x), qkv=fft(qkv) is mathematically equivalent to x=fft(x), qkv=fc(x)
        #    (2) The latter requires fewer FFT computations, delivering higher throughput
        t = self.gate(x)
        x = x.permute(0, 2, 3, 1) # b c h w -> b h w c
        if x.is_cuda and x.dtype == torch.float16:
            x = x.float()
        x = torch.fft.rfft2(x, dim=(1, 2), norm='ortho')
        qkv = self.qkv(x)
        q, k, v = torch.chunk(qkv, chunks=3, dim=-1)

        # Equation 15 of the paper
        #    (1) We use d=1 in practice, as discussed in Table 5
        #    (2) The 1/N factor is implicitly achieved by norm='ortho' in calculating Q, K
        attn = torch.conj(q) * k
        attn = torch.fft.irfft2(attn, s=(h, w), dim=(1, 2), norm='ortho')

        # Equation 16 of the paper
        attn = attn.reshape(b, n, c).softmax(dim=1).reshape(b, h, w, c)
        attn = torch.fft.rfft2(attn, dim=(1, 2))
        x = torch.conj(attn) * v
        x = torch.fft.irfft2(x, s=(h, w), dim=(1, 2), norm='ortho')

        # Output
        x = x.permute(0, 3, 1, 2).to(orig_dtype) * t
        x = self.proj(x)
        return x

class PSABlock_CirculantAtt(PSABlock):
    def __init__(self, c, attn_ratio=0.5, num_heads=4, shortcut=True) -> None:
        super().__init__(c, attn_ratio, num_heads, shortcut)

        self.attn = CirculantAttention(c)

class C2PSA_CirculantAtt(C2PSA):
    def __init__(self, c1, c2, n=1, e=0.5):
        super().__init__(c1, c2, n, e)

注册

在ultralytics/nn/tasks.py中进行如下操作:

步骤1:

from ultralytics.nn.C2PSA.C2PSA_CirculantAtt import C2PSA_CirculantAtt  

步骤2

修改def parse_model(d, ch, verbose=True):


base_modules = frozenset(
    {
        C2PSA_CirculantAtt,
    }
)
repeat_modules = frozenset(  # modules with 'repeat' arguments
    {
        C2PSA_CirculantAtt,
    }
)

配置yolo26-C2PSA_CirculantAtt.yaml

# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license

# Ultralytics YOLO26 object detection model with P3/8 - P5/32 outputs
# Model docs: https://docs.ultralytics.com/models/yolo26
# Task docs: https://docs.ultralytics.com/tasks/detect

# Parameters
nc: 80 # number of classes
end2end: True # whether to use end-to-end mode
reg_max: 1 # DFL bins
scales: # model compound scaling constants, i.e. 'model=yolo26n.yaml' will call yolo26.yaml with scale 'n'
  # [depth, width, max_channels]
  n: [0.50, 0.25, 1024] # summary: 260 layers, 2,572,280 parameters, 2,572,280 gradients, 6.1 GFLOPs
  s: [0.50, 0.50, 1024] # summary: 260 layers, 10,009,784 parameters, 10,009,784 gradients, 22.8 GFLOPs
  m: [0.50, 1.00, 512] # summary: 280 layers, 21,896,248 parameters, 21,896,248 gradients, 75.4 GFLOPs
  l: [1.00, 1.00, 512] # summary: 392 layers, 26,299,704 parameters, 26,299,704 gradients, 93.8 GFLOPs
  x: [1.00, 1.50, 512] # summary: 392 layers, 58,993,368 parameters, 58,993,368 gradients, 209.5 GFLOPs

# YOLO26n backbone
backbone:
  - [-1, 1, Conv, [64, 3, 2]]
  - [-1, 1, Conv, [128, 3, 2]]
  - [-1, 2, C3k2, [256, False, 0.25]]
  - [-1, 1, Conv, [256, 3, 2]]
  - [-1, 2, C3k2, [512, False, 0.25]]
  - [-1, 1, Conv, [512, 3, 2]]
  - [-1, 2, C3k2, [512, True]]
  - [-1, 1, Conv, [1024, 3, 2]]
  - [-1, 2, C3k2, [1024, True]]
  - [-1, 1, SPPF, [1024, 5, 3, True]]
  - [-1, 2, C2PSA_CirculantAtt, [1024]]

head:
  - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  - [[-1, 6], 1, Concat, [1]]
  - [-1, 2, C3k2, [512, True]]
  - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  - [[-1, 4], 1, Concat, [1]]
  - [-1, 2, C3k2, [256, True]]
  - [-1, 1, Conv, [256, 3, 2]]
  - [[-1, 13], 1, Concat, [1]]
  - [-1, 2, C3k2, [512, True]]
  - [-1, 1, Conv, [512, 3, 2]]
  - [[-1, 10], 1, Concat, [1]]
  - [-1, 1, C3k2, [1024, True, 0.5, True]]
  - [[16, 19, 22], 1, Detect, [nc]]

实验

脚本

import warnings
warnings.filterwarnings('ignore')
from ultralytics import YOLO
 
if __name__ == '__main__':
#     修改为自己的配置文件地址
    model = YOLO('./ultralytics/cfg/models/26/yolo26-C2PSA_CirculantAtt.yaml')
#     修改为自己的数据集地址
    model.train(data='./ultralytics/cfg/datasets/coco8.yaml',
                cache=False,
                imgsz=640,
                epochs=10,
                single_cls=False,  # 是否是单类别检测
                batch=8,
                close_mosaic=10,
                workers=0,
                optimizer='MuSGD',  
                # optimizer='SGD',
                amp=False,
                project='runs/train',
                name='C2PSA_CirculantAtt',
                )

结果

image-20261125215636431

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐