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

CompSLOT 槽原语选择

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

计算机视觉计算机视觉持续学习基础模型表征学习

结构图

CompSLOT 槽原语选择结构图
CompSLOT 槽原语选择结构图

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

论文信息

  • 论文:Plug-and-Play Compositionality for Boosting Continual Learning with Foundation Models
  • 出处:ICLR 2026

核心痛点

基础模型做持续学习时容易依赖零散、片段化的概念,学新类就把旧知识覆盖掉;全量微调又会明显遗忘。

模块亮点

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

适用场景

适合基础模型的持续学习与概念组合表示,输入为 B、N、C 的视觉特征。要区分概念学习和分类预测两个阶段,单独抽出时不包含样本蒸馏与持续任务管理,其他任务需单独验证。

插入位置建议

  • 放在视觉特征与分类头之间,先做槽提取和原语选择,再接分类器;槽数、迭代次数、解码位置和 Token 布局要对应,训练时启用重建损失和选择辅助返回。

适用任务

  • 基础模型的持续学习与概念组合表示
  • 输入为 B
  • C 的视觉特征。要区分概念学习和分类预测两个阶段

完整代码

compslot.py
"""165_CompSLOT_ICLR2026: 官方核心模块的单文件提取。

官方源码: https://github.com/liaoweiduo/CompSLOT/blob/e7b721e69a6f33adb573fb7b222ac109de659497/backbone/slot.py
源码 SHA256: b215f84ac5b3e14a7c7cfa1e1c279d8e1b32d3fc4715e156fa8ab9fd8440682b
提取核心: SlotAttention
整理说明: 保留官方槽迭代、解码重建和原语选择计算。默认返回原方法内部的重建特征 [B,N,C],return_aux=True 返回原来的槽/损失/选择字典;未添加虚构反投影。
形状验证只说明接口可用,不代表已复现论文指标。初始化/辅助输入遵循原仓库;
需要语义特征、掩码、时间等条件的模块不能省略对应条件。
"""
from __future__ import annotations

# Upstream repository license: LICENSE
# MIT License
# 
# Copyright (c) 2026 pomelo
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import torch
from torch import nn
import torch.nn.functional as F
import logging
from torch.nn.init import trunc_normal_


class SlotAttention(nn.Module):

    def __init__(self, args, num_patches):
        super().__init__()
        self.task_count = 0
        if 'large' in args['backbone_type']:
            self.emb_d = 1024
        else:
            self.emb_d = 768
        self.key_d = args['slot_dim']
        self.num_patches = num_patches
        logging.debug('key_d: {}, num_patches: {}'.format(self.key_d, self.num_patches))
        self.n_slots = args['n_slots']
        self.n_iter = args['n_iter']
        self.temp = args['slot_temp']
        self.attn_epsilon = 1e-08
        self.gru_d = self.key_d
        logging.debug('n_slots: {}, n_iter: {}, temp: {}'.format(self.n_slots, self.n_iter, self.temp))
        self.ln_input = nn.LayerNorm(self.emb_d)
        self.ln_slot = nn.LayerNorm(self.key_d)
        self.ln_output = nn.LayerNorm(self.key_d)
        self.mu = self.init_tensor(1, 1, self.key_d)
        self.log_sigma = self.init_tensor(1, 1, self.key_d)
        self.k = nn.Linear(self.emb_d, self.key_d, bias=False)
        self.q = nn.Linear(self.key_d, self.key_d, bias=False)
        self.v = nn.Linear(self.emb_d, self.key_d, bias=False)
        self.gru = nn.GRUCell(self.key_d, self.gru_d)
        self.mlp = nn.Sequential(nn.Linear(self.key_d, self.key_d, bias=True), nn.ReLU(inplace=True), nn.Linear(self.key_d, self.key_d, bias=True))
        self.decoder_pos_emb = nn.Parameter(torch.zeros(1, num_patches, 1, self.key_d))
        trunc_normal_(self.decoder_pos_emb, std=0.02)
        self.decoder_mapping_layers = args.get('decoder_mapping_layers', 3)
        decoder_dim = self.key_d * 2
        decoder_layers = [nn.Linear(self.key_d, decoder_dim, bias=True)]
        for _ in range(self.decoder_mapping_layers - 2):
            decoder_layers.append(nn.ReLU(inplace=True))
            decoder_layers.append(nn.Linear(decoder_dim, decoder_dim, bias=True))
        decoder_layers.append(nn.ReLU(inplace=True))
        decoder_layers.append(nn.Linear(decoder_dim, self.emb_d, bias=True))
        self.decoder = nn.Sequential(*decoder_layers)
        self.select_slot_temp = args['select_slot_temp']
        logging.debug('select_slot_temp: {}'.format(self.select_slot_temp))
        self.slot_ln = nn.LayerNorm(self.key_d) if not args.get('disable_ln', False) else nn.Identity()
        self.task_key = nn.Parameter(torch.randn(self.key_d), requires_grad=True)
        self.slot_selection_w = self.init_tensor(self.key_d, self.key_d)
        self.slot_selection_b = self.init_tensor(self.key_d)
        self.debug_verbose = 1

    def process_task_count(self):
        self.task_count += 1

    def forward(self, features, temp=None, n_iter=None, return_aux=False):
        """forward all path
        """
        slots, attn, _ = self.forward_slots(features, temp=temp, n_iter=n_iter)
        slot_features = slots.unsqueeze(1)
        slot_features = slot_features + self.decoder_pos_emb
        slot_features = self.decoder(slot_features)
        slot_features = torch.einsum('bnkd,bnk->bnd', slot_features, attn)
        recon_loss = F.mse_loss(slot_features, features, reduction='none')
        recon_loss = torch.mean(torch.mean(recon_loss, dim=-1), dim=-1)
        w, w_slots = self.forward_selector(slots)
        if self.debug_verbose > 0:
            logging.debug('slots: {} {}'.format(slots.shape, slots[0, 0, :10]))
            logging.debug('attn: {}'.format(attn.shape))
            logging.debug('slot_features: {}'.format(slot_features.shape))
            logging.debug('recon_loss: {} {}'.format(recon_loss.shape, recon_loss[0]))
            logging.debug('w: {} {}'.format(w.shape, w[0]))
            logging.debug('w_slots: {}'.format(w_slots.shape))
            self.debug_verbose -= 1
        return {'slots': slots, 'attns': attn, 'recon_loss': recon_loss, 'w': w, 'w_slots': w_slots} if return_aux else slot_features

    def forward_slots(self, features, temp=None, n_iter=None):
        bs = features.shape[0]
        n_iter = self.n_iter if n_iter is None else n_iter
        temp = self.temp if temp is None else temp
        iter_slots = []
        iter_attn_vis = []
        features = self.ln_input(features)
        slots = torch.randn(bs, self.n_slots, self.key_d, device=self.log_sigma.device) * torch.exp(self.log_sigma) + self.mu
        k = self.k(features)
        v = self.v(features)
        k = self.key_d ** (-0.5) * temp * k
        attn_vis = None
        for t in range(n_iter):
            slots_prev = slots.clone()
            slots = self.ln_slot(slots)
            q = self.q(slots)
            attn = torch.einsum('bnd,bkd->bnk', k, q)
            attn_vis = F.softmax(attn, dim=-1)
            attn = attn_vis + self.attn_epsilon
            attn = attn / torch.sum(attn, dim=-2, keepdim=True)
            updates = torch.einsum('bnk,bnd->bkd', attn, v)
            slots = self.gru(updates.view(-1, self.key_d), slots_prev.reshape(-1, self.key_d))
            slots = slots.view(bs, self.n_slots, self.key_d)
            slots = slots + self.mlp(self.ln_output(slots))
            iter_slots.append(slots.detach().clone())
            iter_attn_vis.append(attn_vis.detach().clone())
        return (slots, attn_vis, {'slots': iter_slots, 'attns': iter_attn_vis})

    def forward_selector(self, slots):
        """aggregate slots

        Args:
            slots (Tensor): [bs, n, d]
        """
        bs, n, h = slots.shape
        w = torch.ones(bs, n).to(slots.device)
        w_slots = None
        slots = self.slot_ln(slots)
        slot_selection_w = self.slot_selection_w
        slot_selection_b = self.slot_selection_b
        mapped_slots = torch.einsum('bnh,hd->bnd', slots, slot_selection_w)
        mapped_slots = mapped_slots + slot_selection_b
        mapped_slots = torch.tanh(mapped_slots)
        task_key = self.task_key
        w = torch.einsum('bnd,d->bn', mapped_slots, task_key)
        w = w * task_key.shape[-1] ** (-0.5)
        w = w * self.select_slot_temp
        w = F.softmax(w, dim=-1)
        w_slots = torch.einsum('bnh,bn->bh', mapped_slots, w)
        return (w, w_slots)

    def init_tensor(self, a, b=None, c=None, d=None, init=True, ortho=False):
        if b is None:
            p = torch.nn.Parameter(torch.FloatTensor(a), requires_grad=True)
        elif c is None:
            p = torch.nn.Parameter(torch.FloatTensor(a, b), requires_grad=True)
        elif d is None:
            p = torch.nn.Parameter(torch.FloatTensor(a, b, c), requires_grad=True)
        else:
            p = torch.nn.Parameter(torch.FloatTensor(a, b, c, d), requires_grad=True)
        if init:
            if ortho:
                nn.init.orthogonal_(p)
            elif b is None:
                nn.init.constant_(p, 0)
            else:
                nn.init.xavier_uniform_(p)
        return p


def main():
    """最小使用示例:创建模块,验证输入与输出形状。"""
    torch.manual_seed(0)
    args = dict(backbone_type='vit_base', slot_dim=16, n_slots=4, n_iter=2, slot_temp=1.0, select_slot_temp=1.0)
    module = SlotAttention(args, num_patches=16)
    input = torch.randn(2, 16, 768)
    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+

继续浏览

下一篇CORD 竞争残差检测在共同观测空间比较良性与越狱动力学对同一后继的预测,以双轴误差对比形成风险分数。输入历史和控制保持一致,使相对拟合有共同参照。

相关资源