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

CLASS 类别引导视觉

把视觉 Token 编码到适配空间,将多模态类别原型投影成条件 Token,用交叉注意力补进稀有对象的语义信息,再经归一化、前馈细化和解码回到原视觉维度。主 VLM 保持冻结,只训练这个旁路适配器。

多模态计算机视觉视觉语言模型多模态目标识别

结构图

CLASS 类别引导视觉结构图
CLASS 类别引导视觉结构图

把视觉 Token 编码到适配空间,将多模态类别原型投影成条件 Token,用交叉注意力补进稀有对象的语义信息,再经归一化、前馈细化和解码回到原视觉维度。主 VLM 保持冻结,只训练这个旁路适配器。

论文信息

  • 论文:Seeing Clearly, Reasoning Confidently: Plug-and-Play Remedies for Vision Language Model Blindness
  • 出处:CVPR 2026

核心痛点

视觉语言模型面对图里的小目标、稀有物体时经常“看不见”,回答漏掉关键对象;重训主模型代价又太高。

模块亮点

  • 把视觉 Token 编码到适配空间,将多模态类别原型投影成条件 Token,用交叉注意力补进稀有对象的语义信息,再经归一化、前馈细化和解码回到原视觉维度。主 VLM 保持冻结,只训练这个旁路适配器。

适用场景

适合视觉语言模型的稀有对象识别与推理增强,可接在视觉编码器输出之后。需要配套训练好的类别原型和匹配的 Token 接口,单独抽出时不包含完整推理流程,其他任务需单独验证。

插入位置建议

  • 放在视觉 Token 进入大模型之前的适配位置,输入末维要与 visual_dim 对齐;核对类别原型数量、通道和类别含义,原型必须来自可信检查点,训练时再配合原语言模型损失。

适用任务

  • 视觉语言模型的稀有对象识别与推理增强
  • 可接在视觉编码器输出之后。需要配套训练好的类别原型和匹配的 Token 接口
  • 单独抽出时不包含完整推理流程

完整代码

seeingclearly.py
"""126_SeeingClearly_CVPR2026: 官方核心模块的单文件提取。

官方源码: https://github.com/XinHu98/seeing/blob/f9c5838947ad9867f43f807ed28f1f8447ff1037/src/seeing/models/adapter.py
源码 SHA256: 7ba748e5b40de6725d6be8873d0bd5ca1bb81c3a36129b8fec381d04e3af53d1
提取核心: ClassGuidedVisualAdapter, AdapterLoss, load_class_embeddings
整理说明: 保留类别原型交叉注意力和视觉 token 编解码;默认返回 refined 特征,return_aux=True 保留官方三元组。类别原型需由训练模型或 load_class_embeddings 提供。
形状验证只说明接口可用,不代表已复现论文指标。初始化/辅助输入遵循原仓库;
需要语义特征、掩码、时间等条件的模块不能省略对应条件。
"""
from __future__ import annotations

import torch
from torch import nn
import torch.nn.functional as F
from pathlib import Path


class ClassGuidedVisualAdapter(nn.Module):
    """Refine frozen VLM visual tokens using learned class embeddings.

    The adapter encodes LLaVA visual tokens into the class-embedding space,
    applies cross-attention over class prototypes, and decodes the refined
    latent tokens back to the language-model embedding dimension.
    """

    def __init__(self, visual_dim: int=4096, latent_dim: int=1024, class_emb_dim: int=1024, num_classes: int=29, num_heads: int=8, dropout: float=0.1) -> None:
        super().__init__()
        self.visual_dim = visual_dim
        self.latent_dim = latent_dim
        self.num_classes = num_classes
        self.encoder = nn.Sequential(nn.Linear(visual_dim, 2048), nn.LayerNorm(2048), nn.GELU(), nn.Dropout(dropout), nn.Linear(2048, latent_dim), nn.LayerNorm(latent_dim))
        self.class_proj = nn.Identity() if class_emb_dim == latent_dim else nn.Linear(class_emb_dim, latent_dim)
        self.cross_attn = nn.MultiheadAttention(embed_dim=latent_dim, num_heads=num_heads, dropout=dropout, batch_first=True)
        self.attn_norm = nn.LayerNorm(latent_dim)
        self.ffn = nn.Sequential(nn.Linear(latent_dim, latent_dim * 4), nn.GELU(), nn.Dropout(dropout), nn.Linear(latent_dim * 4, latent_dim), nn.LayerNorm(latent_dim))
        self.decoder = nn.Sequential(nn.Linear(latent_dim, 2048), nn.LayerNorm(2048), nn.GELU(), nn.Dropout(dropout), nn.Linear(2048, visual_dim))
        self._init_weights()

    def _init_weights(self) -> None:
        for module in self.modules():
            if isinstance(module, nn.Linear):
                nn.init.xavier_normal_(module.weight, gain=0.02)
                if module.bias is not None:
                    nn.init.zeros_(module.bias)
            elif isinstance(module, nn.LayerNorm):
                nn.init.ones_(module.weight)
                nn.init.zeros_(module.bias)

    def forward(self, visual_tokens: torch.Tensor, class_embeddings: torch.Tensor, return_aux=False):
        if visual_tokens.shape[-1] != self.visual_dim:
            raise ValueError(f'Expected visual_dim={self.visual_dim}, got {visual_tokens.shape[-1]}')
        class_embeddings = class_embeddings.to(device=visual_tokens.device, dtype=visual_tokens.dtype)
        latent = self.encoder(visual_tokens)
        class_tokens = self.class_proj(class_embeddings).unsqueeze(0).expand(visual_tokens.shape[0], -1, -1)
        attn_out, attn_weights = self.cross_attn(query=latent, key=class_tokens, value=class_tokens)
        latent = self.attn_norm(latent + attn_out)
        latent = latent + self.ffn(latent)
        refined = self.decoder(latent)
        return (refined, latent, attn_weights) if return_aux else refined


class AdapterLoss(nn.Module):
    """Reconstruction plus autoregressive VQA loss."""

    def __init__(self, reconstruction_weight: float=1.0, autoregressive_weight: float=1.0) -> None:
        super().__init__()
        self.reconstruction_weight = reconstruction_weight
        self.autoregressive_weight = autoregressive_weight

    def forward(self, refined_tokens: torch.Tensor, original_tokens: torch.Tensor, lm_loss: torch.Tensor):
        reconstruction = F.mse_loss(refined_tokens.float(), original_tokens.float())
        total = self.reconstruction_weight * reconstruction + self.autoregressive_weight * lm_loss
        return (total, {'total': float(total.detach().cpu()), 'reconstruction': float(reconstruction.detach().cpu()), 'autoregressive': float(lm_loss.detach().cpu())})


def load_class_embeddings(checkpoint_path: str | Path, device: str | torch.device='cpu') -> torch.Tensor:
    """Load class prototypes from the public checkpoint format."""
    checkpoint = torch.load(checkpoint_path, map_location=device)
    for key in ('bank.w', 'class_embeddings', 'prototypes'):
        if key in checkpoint:
            return checkpoint[key].to(device)
    raise KeyError(f'No class embedding tensor found in {checkpoint_path}. Keys: {sorted(checkpoint.keys())}')


def main():
    """最小使用示例:创建模块,验证输入与输出形状。"""
    torch.manual_seed(0)
    module = ClassGuidedVisualAdapter(visual_dim=32, latent_dim=16, class_emb_dim=16, num_classes=4, num_heads=4, dropout=0)
    input = torch.randn(2,16,32)
    class_embeddings = torch.randn(4,16)
    output = module(input, class_embeddings)
    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+

继续浏览

下一篇SIDMLP 语义前缀预测头一次读取用户历史上下文,再与有序前缀嵌入拼接,由各位置独立的感知机预测。通过蒸馏转移教师行为,训练可并行计算各头,推理仍保留逐位前缀依赖。

相关资源