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

CLAdapter 聚类注意适配

先汇聚序列得到样本描述,与可学习的归一化聚类中心算相关性,用这组权重组合多组变换矩阵;

计算机视觉计算机视觉注意力机制参数高效微调科学视觉NeurIPS2025

结构图

CLAdapter 聚类注意适配结构图
CLAdapter 聚类注意适配结构图

先汇聚序列得到样本描述,与可学习的归一化聚类中心算相关性,用这组权重组合多组变换矩阵;

论文信息

  • 论文:Unleashing Foundation Vision Models: Adaptive Transfer for Diverse Data-Limited Scientific Domains
  • 出处:NEURIPS 2025

核心痛点

大规模预训练视觉模型在科学领域落地时,专用数据往往很少、分布差异又大,全量微调成本高且容易过拟合,普通适配器也很难针对不同特征分布做调整。

模块亮点

  • 先汇聚序列得到样本描述,与可学习的归一化聚类中心算相关性,用这组权重组合多组变换矩阵;特征先降到瓶颈空间做样本相关的变换,再升维,配合归一化和前馈块细化。统一接口可接 CNN 与 Transformer、2D 与 3D 特征。

适用场景

数据有限的科学视觉任务,如医学、生物、工业、农业、遥感、材料等领域的分类与识别;其他任务和主干需在同一微调预算下单独验证。

插入位置建议

  • 放在冻结主干的特征输出之后、分类头之前;输入按 [B, N, C] 序列整理,按主干设置 token 排列、嵌入维度、瓶颈宽度、聚类中心数和块数,聚类中心与变换矩阵均为可学习参数。

适用任务

  • 数据有限的科学视觉任务
  • 如医学
  • 生物

完整代码

cladapter.py
"""58_CLAdapter_NeurIPS2025: 官方核心模块的单文件提取。

官方源码: https://github.com/qklee-lz/CLAdapter/blob/c1632d9793ee73d96ffa0c641be35dbc1ed5805e/CODE/models/modules.py
源码 SHA256: 860ec2a7f8bc722e8c1ce98c49b315e1014d74e8668fe3fe38b94318d013d753
提取核心: Cluster_Attention, FR_Resblock, CLAdapter
整理说明: 完整保留官方 Cluster_Attention、FR_Resblock、CLAdapter 计算;去除注释掉的替代实现,新增 main 示例。输入 [B,N,C];用于特征聚类适配,非完整分类模型。
形状验证只说明接口可用,不代表已复现论文指标。初始化/辅助输入遵循原仓库;
需要语义特征、掩码、时间等条件的模块不能省略对应条件。
"""
from __future__ import annotations

import torch
from torch import nn
from torch.nn import LayerNorm
import torch.nn.functional as F
from collections import OrderedDict
from typing import Callable
from torch.utils.checkpoint import checkpoint


class Cluster_Attention(nn.Module):

    def __init__(self, dim, len_token, centers, temp_dim=256, qkv_bias=False, proj_drop=0.0):
        super().__init__()
        self.centers = nn.Parameter(torch.randn(dim, centers))
        self.tran_ms = nn.Parameter(torch.randn(centers, temp_dim, temp_dim))
        self.down_layer = nn.Linear(dim, temp_dim)
        self.up_layer = nn.Linear(temp_dim, dim)
        self.proj = nn.Linear(dim, dim)
        self.proj_drop = nn.Dropout(proj_drop)

    def forward(self, x):
        q = x.mean(1)
        x = self.down_layer(x)
        B, N, C = x.shape
        attn = torch.mm(F.normalize(q, dim=-1), F.normalize(self.centers, dim=0))
        attn = attn.softmax(dim=-1)
        attn = attn.unsqueeze(-1).unsqueeze(-1).repeat(1, 1, C, C)
        tm = self.tran_ms.unsqueeze(0).expand_as(attn)
        tm = (attn * tm).sum(1)
        x = torch.bmm(x, tm)
        x = self.up_layer(x)
        x = self.proj_drop(x)
        return x


class FR_Resblock(nn.Module):

    def __init__(self, d_model: int, len_token: int, centers: int, mlp_ratio: float=4.0, act_layer: Callable=nn.GELU):
        super().__init__()
        self.ln_1 = LayerNorm(d_model)
        self.attn = Cluster_Attention(d_model, len_token, centers)
        self.ln_2 = LayerNorm(d_model)
        mlp_width = int(d_model * mlp_ratio)
        self.mlp = nn.Sequential(OrderedDict([('c_fc', nn.Linear(d_model, mlp_width)), ('gelu', act_layer()), ('c_proj', nn.Linear(mlp_width, d_model))]))

    def forward(self, x: torch.Tensor):
        x = self.attn(self.ln_1(x))
        x = x + self.mlp(self.ln_2(x))
        return x


class CLAdapter(nn.Module):

    def __init__(self, check_point: list, width: int, len_token: int, centers: int, dt_layers: int, mlp_ratio: float=4.0, act_layer: Callable=nn.GELU):
        super().__init__()
        self.check_point = check_point
        self.da_resblocks = nn.ModuleList([FR_Resblock(width, len_token, centers, mlp_ratio, act_layer=act_layer) for i in range(dt_layers)])

    def forward(self, x: torch.Tensor):
        if self.check_point[0] and (not torch.jit.is_scripting()):
            for idx, dr in enumerate(self.da_resblocks):
                if idx < self.check_point[1]:
                    x = checkpoint(dr, x, use_reentrant=False)
                else:
                    x = dr(x)
        else:
            for dr in self.da_resblocks:
                x = dr(x)
        return x


def main():
    """最小使用示例:创建模块,验证输入与输出形状。"""
    torch.manual_seed(0)
    module = CLAdapter(check_point=[False, 0], width=32, len_token=16, centers=4, dt_layers=1)
    input = torch.randn(2, 16, 32)
    output = module(input)
    assert input.shape == output.shape, (input.shape, output.shape)
    assert torch.isfinite(output).all(), "output contains NaN/Inf"
    print("input shape:", tuple(input.shape))
    print("output shape:", tuple(output.shape))
    return module, input, output


if __name__ == "__main__":
    main()

环境与依赖

Python 3.9+

继续浏览

下一篇CompSLOT 槽原语选择用槽注意力把图像特征迭代分解成一组对象或概念槽,再用解码器和注意力重建原特征,同时估计原语选择权重,把槽组合成可复用的概念原语,接到分类器上辅助持续学习。

相关资源