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

FedTaxo 联邦概念重聚类

用视觉原型与描述嵌入联合评分,在客户端不可合并约束下平均连接重聚类。外层保留所有新类证据并每轮重传,才能修订旧分配;源码不含层级关系与客户端标签映射。

深度学习联邦学习少样本学习增量学习概念对齐约束聚类

结构图

FedTaxo 联邦概念重聚类结构图
FedTaxo 联邦概念重聚类结构图

用视觉原型与描述嵌入联合评分,在客户端不可合并约束下平均连接重聚类。外层保留所有新类证据并每轮重传,才能修订旧分配;源码不含层级关系与客户端标签映射。

论文信息

  • 论文:Learning New Classes Federatively without a Shared Label Space

核心痛点

客户端用不同名称描述同一概念,或用同一名称描述不同概念。把标签字符串直接当全局类别,会让错误合并延续到后续增量会话。

模块亮点

  • 用视觉原型与描述嵌入联合评分,在客户端不可合并约束下平均连接重聚类。外层保留所有新类证据并每轮重传,才能修订旧分配;源码不含层级关系与客户端标签映射。

适用场景

私有标签体系下的联邦少样本增量分类。特征共享不等同隐私保证,其他任务需单独验证。

插入位置建议

  • 放在服务器接收类特征后、概念聚合与本地标签读取前。显式提供客户端编号及全局唯一单元编号,核对[N,d]原型与[N,de]文本嵌入,并校准阈值。

适用任务

  • 私有标签体系下的联邦少样本增量分类。特征共享不
  • 其他任务需单独验证

完整代码

fedtaxo.py
# -*- coding: utf-8 -*-
"""FedTaxo——无共享标签空间的联邦新类概念对齐模块。

问题:联邦少样本类增量学习中,各客户端用私有、部分重叠的分类法命名新类(同义词、同形异义词),
服务器无对应关系,须判定客户端新类是否同一概念。
方法:把每个本地类编码为概念胶囊(shot 嵌入、原型、描述嵌入),用视觉/文本双通道余弦加权匹配分
打分,在"同一客户端的两个标识绝不合并"的 cannot-link 约束下,对全部新胶囊做约束平均连接重聚类,
仅当连接度达到阈值 τ 才提交合并,且每会话可撤销旧合并。
作用:即插即用的约束重新分配算子,输入胶囊原型与文本嵌入,输出概念节点编号与匹配分。
论文:"Learning New Classes Federatively without a Shared Label Space"(FedTaxo)。
"""

from typing import Optional

import torch
import torch.nn.functional as F


class FedTaxo(torch.nn.Module):
    """Constrained, revisable concept re-clustering head (paper Sec. 3.2).

    Given per-class "concept capsules" (a shot-weighted prototype and a description
    embedding), score every capsule pair by the fused cosine and merge clusters by
    constrained average linkage, never merging two clusters that share a client.
    """

    def __init__(
        self,
        w_vis: float = 0.6,
        w_txt: float = 0.4,
        tau: float = 0.3,
        max_merges: Optional[int] = None,
    ) -> None:
        super().__init__()
        self.w_vis = float(w_vis)
        self.w_txt = float(w_txt)
        self.tau = float(tau)
        self.max_merges = max_merges

    @torch.no_grad()
    def _cluster(
        self,
        p: torch.Tensor,            # (N, d) prototypes
        e: Optional[torch.Tensor],  # (N, de) text embeddings, same space per channel
        client_ids: Optional[torch.Tensor],  # (N,) long, owner client of each capsule
        unit_ids: Optional[torch.Tensor],    # (N,) long, must-linked unit id
        tau: float,
    ):
        n = p.shape[0]
        p = F.normalize(p.float(), dim=-1)
        if e is not None:
            e = F.normalize(e.float(), dim=-1)
            s = self.w_vis * (p @ p.t()) + self.w_txt * (e @ e.t())
        else:
            s = p @ p.t()                       # text channel missing -> visual only
        s = 0.5 * (s + s.t())                   # (N, N) symmetric pair score

        if client_ids is None:
            client_ids = torch.zeros(n, dtype=torch.long, device=p.device)
        else:
            client_ids = client_ids.long().to(p.device)
        onehot = F.one_hot(client_ids).float()  # (N, C)

        # capsules a client sent under one identifier form a must-linked unit
        if unit_ids is None:
            members = [[i] for i in range(n)]
        else:
            unit_ids = unit_ids.long().to(p.device)
            members = [
                torch.nonzero(unit_ids == u, as_tuple=False).flatten().tolist()
                for u in torch.unique(unit_ids).tolist()
            ]

        k = len(members)
        mask = torch.zeros(k, n, dtype=s.dtype, device=s.device)  # cluster membership
        for i, m in enumerate(members):
            mask[i, m] = 1.0

        budget = self.max_merges if self.max_merges is not None else k - 1
        while mask.shape[0] > 1 and budget > 0:
            cnt = mask.sum(1, keepdim=True)                      # (K, 1) sizes
            link = (mask @ s @ mask.t()) / (cnt @ cnt.t())       # (K, K) avg linkage
            own = mask @ onehot                                  # (K, C) client occupancy
            shares = (own > 0).float() @ (own > 0).float().t() > 0
            link = link.masked_fill(shares, float("-inf"))       # cannot-link constraint
            link.fill_diagonal_(float("-inf"))
            best = link.max()
            if not torch.isfinite(best) or best.item() < tau:
                break                                            # below threshold: stop
            ij = torch.nonzero(link == best, as_tuple=False)[0]
            i, j = int(ij[0]), int(ij[1])
            union = (mask[i] + mask[j]).clamp(max=1.0).unsqueeze(0)
            keep = [r for r in range(mask.shape[0]) if r not in (i, j)]
            mask = torch.cat([mask[keep], union], dim=0)
            budget -= 1

        labels = (mask > 0).float().argmax(dim=0)                # (N,) node index
        return labels, s

    def forward(
        self,
        p: torch.Tensor,                       # (N, d) or (B, N, d) prototypes
        e: Optional[torch.Tensor] = None,      # (N, de) or (B, N, de) text embeddings
        client_ids: Optional[torch.Tensor] = None,  # (N,) or (B, N) long
        unit_ids: Optional[torch.Tensor] = None,    # (N,) or (B, N) long
        tau: Optional[float] = None,
        return_affinity: bool = False,
    ):
        """Return concept labels (N,) in [0, K) or (B, N), plus the (N, N) score matrix."""
        tau = self.tau if tau is None else float(tau)
        if p.dim() not in (2, 3):
            raise ValueError("p must be (N, d) or (B, N, d)")
        if e is not None and e.dim() not in (2, 3):
            raise ValueError("e must be (N, de) or (B, N, de), or None")
        batched = p.dim() == 3
        if batched:
            b, n = p.shape[0], p.shape[1]
            if e is not None and e.dim() == 2:
                e = e.unsqueeze(0).expand(b, -1, -1)
            if client_ids is not None and client_ids.dim() == 1:
                client_ids = client_ids.unsqueeze(0).expand(b, -1)
            if unit_ids is not None and unit_ids.dim() == 1:
                unit_ids = unit_ids.unsqueeze(0).expand(b, -1)
        else:
            p, b, n = p.unsqueeze(0), 1, p.shape[0]
            e = None if e is None else e.unsqueeze(0)
            client_ids = None if client_ids is None else client_ids.unsqueeze(0)
            unit_ids = None if unit_ids is None else unit_ids.unsqueeze(0)

        labels, affs = [], []
        for i in range(b):
            out = self._cluster(
                p[i],
                None if e is None else e[i],
                None if client_ids is None else client_ids[i],
                None if unit_ids is None else unit_ids[i],
                tau,
            )
            labels.append(out[0])
            affs.append(out[1])

        labels, affinity = torch.stack(labels), torch.stack(affs)
        if not batched:
            labels, affinity = labels[0], affinity[0]
        return (labels, affinity) if return_affinity else labels


if __name__ == "__main__":
    import sys

    sys.stdout.reconfigure(encoding="utf-8")
    torch.manual_seed(0)

    B, N, d, de, C = 2, 9, 16, 12, 3
    # three latent concepts, each spread over different clients (a true correspondence)
    concepts = torch.randn(3, d)
    owner = torch.tensor([0, 1, 2, 0, 1, 2, 0, 1, 2])
    p = torch.stack([concepts[i // 3] + 0.35 * torch.randn(d) for i in range(N)])
    e = torch.stack([concepts[i // 3, :de] + 0.35 * torch.randn(de) for i in range(N)])
    p = F.normalize(p, dim=-1).unsqueeze(0).expand(B, -1, -1).contiguous()
    e = F.normalize(e, dim=-1).unsqueeze(0).expand(B, -1, -1).contiguous()
    client_ids = owner.unsqueeze(0).expand(B, -1).contiguous()

    head = FedTaxo(w_vis=0.6, w_txt=0.4, tau=0.3)
    labels, affinity = head(p, e, client_ids, return_affinity=True)

    print("prototypes      :", tuple(p.shape), "text:", tuple(e.shape))
    print("client_ids      :", tuple(client_ids.shape))
    print("affinity        :", tuple(affinity.shape))
    print("concept labels  :", tuple(labels.shape), labels[0].tolist())
    print("num concepts    :", int(labels.max()) + 1)

环境与依赖

Python 3.9+

继续浏览

下一篇FMuon 联邦正交动量用聚合动量初始化本地状态,正交化本地动量后再混合全局参考方向。单步代码输出更新方向,完整联邦系统负责跨轮共享与聚合,理论结论有精确方向和步长日程等条件。

相关资源