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

TAR 令牌感知细化

拆成三个部件协同处理。TRM 用 Token 范数统计估计可靠性,做重加权和筛选;CATS 结合全局表示计算条件权重,并加一致性正则;GRM 再把聚合后的局部信息门控注入全局特征。

计算机视觉计算机视觉细粒度分类类别发现注意力机制

结构图

TAR 令牌感知细化结构图
TAR 令牌感知细化结构图

拆成三个部件协同处理。TRM 用 Token 范数统计估计可靠性,做重加权和筛选;CATS 结合全局表示计算条件权重,并加一致性正则;GRM 再把聚合后的局部信息门控注入全局特征。

论文信息

  • 论文:TAR: Token-Aware Refinement for Fine-Grained Generalized Category Discovery
  • 出处:CVPR 2026

核心痛点

细粒度广义类别发现里,少数 Token 响应过强会把注意力带偏,已知类和未知类之间的边界因此变模糊,普通池化很难压住这种噪声。

模块亮点

  • 拆成三个部件协同处理。TRM 用 Token 范数统计估计可靠性,做重加权和筛选;CATS 结合全局表示计算条件权重,并加一致性正则;GRM 再把聚合后的局部信息门控注入全局特征。

适用场景

适合同时包含已知与未知类别的细粒度类别发现,需要原主干提供全局特征和 register Token。单独抽出时不包含完整类别发现训练,其他任务需单独验证。

插入位置建议

  • 接在主干 Token 序列与分类头之间,主输入是批量全局特征、辅助输入是 Token 序列;核对通道数、Token 数、筛选比例和门控范围,训练时接上辅助 KL 与一致性损失。

适用任务

  • 同时包含已知与未知类别的细粒度类别发现
  • 需要原主干提供全局特征和 register Token。单独抽出时不包含完整类别发现训练
  • 其他任务需单独验证

完整代码

tar.py
"""158_TAR_CVPR2026: 官方核心模块的单文件提取。

官方源码: https://github.com/VectorYangYiStar/TAR/blob/731e4b33741b66b40a1b5f01a341648adc834311/model.py
源码 SHA256: b9bda09ddc109ea57a38aabb9d46d6e40d031d1919cccc085925db14148dbae6
提取核心: TRM, CATS, GRM, Mlp
整理说明: 保留官方 TRM 可靠性筛选、CATS 条件权重与正则项、GRM 门控融合。包装类仅组合原仓库调用;主输入为全局特征,辅助输入为 register token。
形状验证只说明接口可用,不代表已复现论文指标。初始化/辅助输入遵循原仓库;
需要语义特征、掩码、时间等条件的模块不能省略对应条件。
"""
from __future__ import annotations

# Upstream repository license: LICENSE.txt
# MIT License
# 
# Copyright (c) 2026 VectorYangYiStar
# 
# 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


class TRM(nn.Module):

    def __init__(self, top_m_ratio: float=0.33, alpha: float=2.0):
        super().__init__()
        self.top_m_ratio = top_m_ratio
        self.alpha = alpha

    def forward(self, Z):
        B, T, D = Z.shape
        norms = Z.norm(dim=-1)
        mu = norms.mean(dim=1, keepdim=True)
        sigma = norms.std(dim=1, keepdim=True) + 1e-06
        zscore = (norms - mu) / sigma
        w = torch.sigmoid(-self.alpha * zscore)
        z_tilde = Z * w.unsqueeze(-1)
        M = max(1, int(self.top_m_ratio * T))
        topk_idx = torch.topk(w, k=M, dim=1, largest=True).indices
        mask = torch.zeros_like(w, dtype=torch.float32)
        mask.scatter(1, topk_idx, 1.0)
        mask = mask > 0
        return (z_tilde, mask, w)


class CATS(nn.Module):

    def __init__(self, dim: int, score_hidden: int=256, tau: float=0.8, beta_kl: float=0.6, lambda_cons: float=0.5, perturb_sigma: float=0.03, use_dot_product: bool=True):
        super().__init__()
        self.tau = tau
        self.beta_kl = beta_kl
        self.lambda_cons = lambda_cons
        self.perturb_sigma = perturb_sigma
        self.use_dot_product = use_dot_product
        if self.use_dot_product:
            self.wx = nn.Linear(dim, dim, bias=False)
            self.wz = nn.Linear(dim, dim, bias=False)
        else:
            self.scorer = Mlp(in_features=dim * 3, hidden_features=score_hidden, out_features=1, drop=0.0)
        self.apply(self._init_weights)

    def _init_weights(self, m):
        if isinstance(m, nn.Linear):
            torch.nn.init.trunc_normal_(m.weight, std=0.02)
            if isinstance(m, nn.Linear) and m.bias is not None:
                nn.init.constant_(m.bias, 0)

    def _score(self, x: torch.Tensor, Z: torch.Tensor):
        B, T, D = Z.shape
        if self.use_dot_product:
            q = self.wx(x).unsqueeze(1)
            k = self.wz(Z)
            s = (q * k).sum(dim=-1) / D ** 0.5
        else:
            x_rep = x.unsqueeze(1).expand(-1, T, -1)
            feat = torch.cat([x_rep, Z, x_rep * Z], dim=-1)
            s = self.scorer(feat).squeeze(-1)
        return s

    def _masked_softmax(self, s: torch.Tensor, mask: torch.Tensor):
        s = s.float()
        very_neg = -1000000000.0
        s_masked = torch.where(mask, s / self.tau, torch.full_like(s, very_neg))
        s_masked = s_masked - s_masked.max(dim=1, keepdim=True).values
        pi = F.softmax(s_masked, dim=1)
        pi = pi * mask.float()
        z = pi.sum(dim=1, keepdim=True).clamp_min(1e-12)
        pi = pi / z
        return pi.to(mask.dtype if mask.dtype.is_floating_point else torch.float32)

    def _kl_to_uniform(self, pi: torch.Tensor, mask: torch.Tensor):
        pi_masked = pi * mask.float()
        M = mask.sum(dim=1).clamp_min(1)
        eps = 1e-12
        H = -(pi_masked * pi_masked.clamp_min(eps).log()).sum(dim=1)
        kl = torch.log(M.float()) - H
        return kl.mean()

    def _consistency(self, x: torch.Tensor, Z: torch.Tensor, mask: torch.Tensor, pi: torch.Tensor):
        noise = torch.zeros_like(Z).normal_(mean=0.0, std=self.perturb_sigma)
        Zp = Z + noise * mask.float().unsqueeze(-1)
        s_prime = self._score(x, Zp)
        pi_prime = self._masked_softmax(s_prime, mask)
        eps = 1e-12
        kl1 = (pi * (pi.clamp_min(eps).log() - pi_prime.clamp_min(eps).log())).sum(dim=1)
        kl2 = (pi_prime * (pi_prime.clamp_min(eps).log() - pi.clamp_min(eps).log())).sum(dim=1)
        return 0.5 * (kl1 + kl2).mean()

    def forward(self, x: torch.Tensor, Z_tlide: torch.Tensor, mask: torch.Tensor, if_compute_loss=True):
        s = self._score(x, Z_tlide)
        pi = self._masked_softmax(s, mask)
        if if_compute_loss:
            loss_kl = self._kl_to_uniform(pi, mask) * self.beta_kl
            loss_cons = self._consistency(x, Z_tlide, mask, pi) * self.lambda_cons
            return (pi, loss_kl, loss_cons)
        else:
            return (pi, None, None)


class GRM(nn.Module):

    def __init__(self, dim: int, bottleneck: int=256, gate_learnable_clamp: bool=True):
        super().__init__()
        self.proj_z = nn.Linear(dim, dim, bias=False)
        self.ln = nn.LayerNorm(dim)
        self.mlp = nn.Sequential(nn.Linear(dim, bottleneck), nn.GELU(), nn.Linear(bottleneck, dim))
        self.gate_affine = nn.Linear(dim * 2, 1)
        self.use_clamp = gate_learnable_clamp
        if self.use_clamp:
            self.alpha = nn.Parameter(torch.tensor(1.2))
            self.beta = nn.Parameter(torch.tensor(-0.1))
        self.apply(self._init_weights)

    def _init_weights(self, m):
        if isinstance(m, nn.Linear):
            torch.nn.init.trunc_normal_(m.weight, std=0.02)
            if isinstance(m, nn.Linear) and m.bias is not None:
                nn.init.constant_(m.bias, 0)

    def forward(self, x: torch.Tensor, Z_tlide: torch.Tensor, pi: torch.Tensor):
        Zp = self.proj_z(Z_tlide)
        a = torch.einsum('bt,btd->bd', pi, Zp)
        a = self.ln(a)
        a = a + 0.5 * self.mlp(a)
        gate_inp = torch.cat([x, a], dim=-1)
        g_lin = self.gate_affine(gate_inp)
        if self.use_clamp:
            gamma = self.alpha * torch.sigmoid(g_lin) + self.beta
        else:
            gamma = torch.sigmoid(g_lin) * F.silu(g_lin)
        v = x + gamma * a
        return (v, a)


class Mlp(nn.Module):

    def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0):
        super().__init__()
        out_features = out_features or in_features
        hidden_features = hidden_features or in_features
        self.fc1 = nn.Linear(in_features, hidden_features)
        self.act = act_layer()
        self.fc2 = nn.Linear(hidden_features, out_features)
        self.drop = nn.Dropout(drop)

    def forward(self, x):
        x = self.fc1(x)
        x = self.act(x)
        x = self.drop(x)
        x = self.fc2(x)
        x = self.drop(x)
        return x
class TARAdapter(nn.Module):
    """按官方 DINOHead 中 TRM -> CATS -> GRM 的调用顺序组合。"""
    def __init__(self, dim, bottleneck=64):
        super().__init__()
        self.trm = TRM()
        self.cats = CATS(dim)
        self.grm = GRM(dim, bottleneck)

    def forward(self, x, register_tokens, return_aux=False):
        tokens, mask, weights = self.trm(register_tokens)
        pi, loss_kl, loss_cons = self.cats(x, tokens, mask)
        refined, aggregate = self.grm(x, tokens, pi)
        if return_aux:
            return refined, dict(pi=pi, mask=mask, weights=weights, loss_kl=loss_kl, loss_cons=loss_cons, aggregate=aggregate)
        return refined



def main():
    """最小使用示例:创建模块,验证输入与输出形状。"""
    torch.manual_seed(0)
    module = TARAdapter(32)
    input = torch.randn(2,32)
    register_tokens = torch.randn(2,12,32)
    output = module(input, register_tokens)
    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+

继续浏览

下一篇TBGA 时序几何交互把场景几何 token 与 ego 相机轨迹 token 放进同一个 softmax,按来源各学一个时间尺度,用负 beta 乘时间差的平方压低远离查询的上下文;

相关资源