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

Agent Attention 代理注意力

代理聚合广播:在 (Q,K,V) 之外引入少量 Agent token,先代理 Query 从 K、V 聚合全局信息,再广播回每个 Query,兼得 Softmax 表达力与线性复杂度

计算机视觉计算机视觉注意力机制AgentAttention

结构图

Agent Attention 代理注意力结构图
Agent Attention 代理注意力结构图

代理聚合广播:在 (Q,K,V) 之外引入少量 Agent token,先代理 Query 从 K、V 聚合全局信息,再广播回每个 Query,兼得 Softmax 表达力与线性复杂度

论文信息

  • 论文:Agent Attention: On the Integration of Softmax and Linear Attention
  • 出处:arXiv 2023

核心痛点

Softmax 注意力两两计算 query-key 相似度,复杂度随 token 数二次增长,高分辨率算不起;线性注意力表达力又不足——效率与表达力长期二选一。

模块亮点

  • 代理聚合广播:在 (Q,K,V) 之外引入少量 Agent token,先代理 Query 从 K、V 聚合全局信息,再广播回每个 Query,兼得 Softmax 表达力与线性复杂度
  • 消融步步涨点:Swin-T 换线性注意力只有 77.8,换成 Agent 注意力升到 79.0,加 Agent Bias 到 81.1,再加 DWC 到 82.6,反超原版 Swin-T 的 81.3
  • 通用免训练加速:DeiT/PVT/Swin/CSwin 四种骨干 ImageNet 全涨,Agent-PVT-S 达 82.2(+2.4);COCO 检测 box AP 最多 +4.7,ADE20K 分割 mIoU 最高 +3.61;插入 Stable Diffusion 免训练即提速 1.84 倍

适用场景

领域为 2D 计算机视觉;原文验证了 ImageNet-1K 分类、COCO 检测与实例分割、ADE20K 语义分割,并免训练接入 Stable Diffusion 加速文生图。

插入位置建议

  • 直接替换 DeiT、PVT、Swin、CSwin 等 Transformer 块中的 Softmax / 窗口注意力
  • 优先换分辨率高的浅中层 stage,替换前三个 stage 收益最大
  • 免训练插入 Stable Diffusion / ToMeSD 的自注意力层,在扩散早期步启用

适用任务

  • 2D 计算机视觉

完整代码

agent-attention.py
import torch
import torch.nn as nn
from timm.models.layers import trunc_normal_

"""
注意力机制 (Attention module) 是 Transformers 中的关键组成部分。虽然全局的注意力机制具有很高的表征能力,但其计算成本较大,限制了其在各种场景下的适用性。
本文提出一种新的注意力范式 Agent Attention, 目的在计算效率和表征能力之间取得良好的平衡。具体而言, Agent Attention 表示为四元组(Q,A,K,V) , 在传统的注意力模块中引入了一组额外的 Agent token A 。
Agent token 首先充当 Query token  Q的代理来聚合来自 K 和 V 的信息, 然后将信息广播回  Q。鉴于 Agent token A的数量可以设计为远小于 Query token Q的数量, 代理注意力明显比 Softmax 注意力更有效, 
同时保留了全局上下文建模能力。

有趣的是,本文展示了 Agent attention 等效于 Linear attention 的广义形式。因此,代理注意力无缝集成了强大的 Softmax attention 和高效的 Linear attention。

作者通过大量实验表明,Agent attention 在各种视觉任务中证明了有效性,包括图像分类、目标检测、语义分割和图像生成。
而且,代理注意力在高分辨率场景中表现出显着的性能,这得益于其线性注意力性质。例如,当应用于 Stable Diffusion 时,Agent attention 会加速生成并显着提高图像生成质量,且无需任何额外的训练。
"""


class AgentAttention(nn.Module):
    def __init__(self, dim, num_patches, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.,
                 sr_ratio=1, agent_num=49, **kwargs):
        super().__init__()
        assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."

        self.dim = dim
        self.num_patches = num_patches
        window_size = (int(num_patches ** 0.5), int(num_patches ** 0.5))
        self.window_size = window_size
        self.num_heads = num_heads
        head_dim = dim // num_heads
        self.scale = head_dim ** -0.5

        self.q = nn.Linear(dim, dim, bias=qkv_bias)
        self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
        self.attn_drop = nn.Dropout(attn_drop)
        self.proj = nn.Linear(dim, dim)
        self.proj_drop = nn.Dropout(proj_drop)

        self.sr_ratio = sr_ratio
        if sr_ratio > 1:
            self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
            self.norm = nn.LayerNorm(dim)

        self.agent_num = agent_num
        self.dwc = nn.Conv2d(in_channels=dim, out_channels=dim, kernel_size=(3, 3), padding=1, groups=dim)
        self.an_bias = nn.Parameter(torch.zeros(num_heads, agent_num, 7, 7))
        self.na_bias = nn.Parameter(torch.zeros(num_heads, agent_num, 7, 7))
        self.ah_bias = nn.Parameter(torch.zeros(1, num_heads, agent_num, window_size[0] // sr_ratio, 1))
        self.aw_bias = nn.Parameter(torch.zeros(1, num_heads, agent_num, 1, window_size[1] // sr_ratio))
        self.ha_bias = nn.Parameter(torch.zeros(1, num_heads, window_size[0], 1, agent_num))
        self.wa_bias = nn.Parameter(torch.zeros(1, num_heads, 1, window_size[1], agent_num))
        trunc_normal_(self.an_bias, std=.02)
        trunc_normal_(self.na_bias, std=.02)
        trunc_normal_(self.ah_bias, std=.02)
        trunc_normal_(self.aw_bias, std=.02)
        trunc_normal_(self.ha_bias, std=.02)
        trunc_normal_(self.wa_bias, std=.02)
        pool_size = int(agent_num ** 0.5)
        self.pool = nn.AdaptiveAvgPool2d(output_size=(pool_size, pool_size))
        self.softmax = nn.Softmax(dim=-1)

    def forward(self, x, H, W):
        b, n, c = x.shape
        num_heads = self.num_heads
        head_dim = c // num_heads
        q = self.q(x)

        if self.sr_ratio > 1:
            x_ = x.permute(0, 2, 1).reshape(b, c, H, W)
            x_ = self.sr(x_).reshape(b, c, -1).permute(0, 2, 1)
            x_ = self.norm(x_)
            kv = self.kv(x_).reshape(b, -1, 2, c).permute(2, 0, 1, 3)
        else:
            kv = self.kv(x).reshape(b, -1, 2, c).permute(2, 0, 1, 3)
        k, v = kv[0], kv[1]

        agent_tokens = self.pool(q.reshape(b, H, W, c).permute(0, 3, 1, 2)).reshape(b, c, -1).permute(0, 2, 1)
        q = q.reshape(b, n, num_heads, head_dim).permute(0, 2, 1, 3)
        k = k.reshape(b, n // self.sr_ratio ** 2, num_heads, head_dim).permute(0, 2, 1, 3)
        v = v.reshape(b, n // self.sr_ratio ** 2, num_heads, head_dim).permute(0, 2, 1, 3)
        agent_tokens = agent_tokens.reshape(b, self.agent_num, num_heads, head_dim).permute(0, 2, 1, 3)

        kv_size = (self.window_size[0] // self.sr_ratio, self.window_size[1] // self.sr_ratio)
        position_bias1 = nn.functional.interpolate(self.an_bias, size=kv_size, mode='bilinear')
        position_bias1 = position_bias1.reshape(1, num_heads, self.agent_num, -1).repeat(b, 1, 1, 1)
        position_bias2 = (self.ah_bias + self.aw_bias).reshape(1, num_heads, self.agent_num, -1).repeat(b, 1, 1, 1)
        position_bias = position_bias1 + position_bias2
        agent_attn = self.softmax((agent_tokens * self.scale) @ k.transpose(-2, -1) + position_bias)
        agent_attn = self.attn_drop(agent_attn)
        agent_v = agent_attn @ v

        agent_bias1 = nn.functional.interpolate(self.na_bias, size=self.window_size, mode='bilinear')
        agent_bias1 = agent_bias1.reshape(1, num_heads, self.agent_num, -1).permute(0, 1, 3, 2).repeat(b, 1, 1, 1)
        agent_bias2 = (self.ha_bias + self.wa_bias).reshape(1, num_heads, -1, self.agent_num).repeat(b, 1, 1, 1)
        agent_bias = agent_bias1 + agent_bias2
        q_attn = self.softmax((q * self.scale) @ agent_tokens.transpose(-2, -1) + agent_bias)
        q_attn = self.attn_drop(q_attn)
        x = q_attn @ agent_v

        x = x.transpose(1, 2).reshape(b, n, c)
        v = v.transpose(1, 2).reshape(b, H // self.sr_ratio, W // self.sr_ratio, c).permute(0, 3, 1, 2)
        if self.sr_ratio > 1:
            v = nn.functional.interpolate(v, size=(H, W), mode='bilinear')
        x = x + self.dwc(v).permute(0, 2, 3, 1).reshape(b, n, c)

        x = self.proj(x)
        x = self.proj_drop(x)
        return x



if __name__ == '__main__':
    dim = 64
    num_patches = 49

    block = AgentAttention(dim=dim, num_patches=num_patches)

    H, W = 7, 7
    x = torch.rand(1, num_patches, dim)

    # Forward pass
    output = block(x, H, W)
    print(f"Input size: {x.size()}")
    print(f"Output size: {output.size()}")

环境与依赖

Python 3.9+

继续浏览

下一篇AKConv 可变核卷积参数量任意:坐标生成算法让卷积核能取 1、2、3、4、5、6、7… 任意数量的参数,标准卷积和 Deformable Conv 都做不到;参数量随核大小线性增长

相关资源