AI Wiki中文/EN

Clustering-based self-supervision

聚类式自监督

Compute balanced soft assignments and swapped-view gradients without confusing balance with separation.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with the problem

Without labels, a model can still group examples and use those groups as temporary training targets. DeepCluster alternates between k-means on current features and supervised prediction of the resulting cluster IDs. The grouping itself changes as the encoder changes; cluster names do not arrive with human semantics. Deep Clustering for Unsupervised Learning of Visual Features

SwAV connects augmented views through prototype assignments. A view predicts the assignment computed from another view, with a batch-level balancing constraint. This avoids treating every training example as a separate named class. Unsupervised Learning of Visual Features by Contrasting Cluster Assignments

We implement a small SwAV-style calculation with three fixed prototype vectors and a four-parameter encoder. Fixing prototypes and omitting image backbones are explicit simplifications; original SwAV learns prototypes jointly with its encoder. The key questions are how balancing works, where gradients stop and what balancing does not guarantee.

Definitions and derivation

Let sik=hi⊤cks_{ik}=h_i^\top c_k score example i against prototype k. With B examples and K prototypes, define a soft assignment matrix q whose rows sum to one and columns to B/K. Entropy encourages a smooth solution:

max⁡q≥0 ∑i,kqiksik+ϵH(q),H(q)=−∑i,kqiklog⁡qik,q1K=1B,q⊤1B=BK1K.\max_{q\ge0}\ \sum_{i,k}q_{ik}s_{ik}+\epsilon H(q),\qquad H(q)=-\sum_{i,k}q_{ik}\log q_{ik},\qquad q\mathbf1_K=\mathbf1_B,\quad q^\top\mathbf1_B=\frac BK\mathbf1_K.

The paper writes an equivalent transposed matrix with total mass one; our returned q contains per-example probabilities. Initialize an exponential score matrix and alternately rescale rows and columns. In the program Q has total mass near one during iteration and q=BQ afterward:

Qik∝esik/ϵ,Qik←QikB∑jQij,Qik←QikK∑jQjk,q=BQ.Q_{ik}\propto e^{s_{ik}/\epsilon},\qquad Q_{ik}\leftarrow\frac{Q_{ik}}{B\sum_jQ_{ij}},\qquad Q_{ik}\leftarrow\frac{Q_{ik}}{K\sum_jQ_{jk}},\qquad q=BQ.

The two rescaling expressions apply sequentially to the current matrix. Finite iterations only approximate both marginals simultaneously; the code performs a final row normalization and tests the column residual. Temperature epsilon controls assignment smoothness, while tau separately controls the student’s prediction distribution.

For two views A and B, hold their assignments fixed while differentiating the swapped cross-entropy:

L=−12B∑i,k[sg⁡(qikA)log⁡pikB+sg⁡(qikB)log⁡pikA],piv=softmax⁡(siv/τ),∇siAL=piA−qiB2Bτ.L=-\frac1{2B}\sum_{i,k}\left[\operatorname{sg}(q^A_{ik})\log p^B_{ik}+\operatorname{sg}(q^B_{ik})\log p^A_{ik}\right],\qquad p^v_i=\operatorname{softmax}(s^v_i/\tau),\quad \nabla_{s^A_i}L=\frac{p^A_i-q^B_i}{2B\tau}.

Backpropagate through the fixed prototype multiplication and tanh encoder, summing both uses of the shared weights. Target recomputation happens between parameter steps. Assignment work costs O(BKd)O(BKd) for d-dimensional scores plus O(SBK)O(SBK) for S scaling iterations; no pairwise B-by-B feature matrix is required. This is the mechanism in SwAV’s assignment and swapped-prediction sections, with our stated architectural simplifications. Unsupervised Learning of Visual Features by Contrasting Cluster Assignments

Run the calculation

Run CPython 3.12.4 with NumPy 1.26.4. Six examples form two nearby points around each prototype. We use epsilon 0.3, tau 0.5 and 500 balancing iterations, then take 150 encoder steps at rate 0.1. Swapped loss falls from 0.914840165 to 0.144216102. The final soft mass is approximately two per prototype, and this particular run also has two hard argmax assignments per prototype. Those hard counts are a measured result, not a consequence guaranteed by soft balancing.

import numpy as np

PROTOTYPES=np.array([[1.,0],[-.5,np.sqrt(3)/2],[-.5,-np.sqrt(3)/2]])


def views():
    x=np.repeat(PROTOTYPES,2,axis=0)+np.tile([[.1,-.15],[-.1,.15]],(3,1));return x,x@np.array([[.9,.1],[-.1,1.1]])


def softmax(logits):
    a=logits-logits.max(axis=1,keepdims=True);e=np.exp(a);return e/e.sum(axis=1,keepdims=True)


def assignments(scores,epsilon=.3,steps=500):
    if scores.ndim!=2 or min(scores.shape)<1 or not np.isfinite(scores).all() or epsilon<=0 or steps<1 or (scores.max()-scores.min())/epsilon>600:raise ValueError('Use a finite score matrix, positive epsilon and positive iteration count.')
    b,k=scores.shape;q=np.exp((scores-scores.max())/epsilon);q/=q.sum()
    for _ in range(steps):q*=((1/b)/q.sum(axis=1))[:,None];q*=((1/k)/q.sum(axis=0))[None,:]
    q*=((1/b)/q.sum(axis=1))[:,None];return b*q


def targets(w):return [assignments(np.tanh(x@w)@PROTOTYPES.T) for x in views()]


def objective(w,frozen_targets):
    loss=0.;gradient=np.zeros_like(w)
    for view,x in enumerate(views()):
        h=np.tanh(x@w);logits=h@PROTOTYPES.T/.5;p=softmax(logits);target=frozen_targets[1-view];logp=logits-logits.max(axis=1,keepdims=True);logp-=np.log(np.exp(logp).sum(axis=1,keepdims=True));loss-=.5*np.mean(np.sum(target*logp,axis=1));gh=.5*(p-target)@PROTOTYPES/(.5*len(x));gradient+=x.T@(gh*(1-h*h))
    return float(loss),gradient


def initial():return np.array([[.3,1.],[.1,.2]])


def train(steps=150):
    w=initial();start=objective(w,targets(w))[0]
    for _ in range(steps):w-=.1*objective(w,targets(w))[1]
    return w,start,objective(w,targets(w))[0]


if __name__=='__main__':
    w,start,end=train();q=targets(w)[0];print('swapped prediction loss',round(start,9),round(end,9),'assignment mass per prototype',q.sum(axis=0).round(9).tolist(),'hard assignment counts',np.bincount(q.argmax(axis=1),minlength=3).tolist())
    scores=np.tile([2.,0.,0.],(6,1));balanced=assignments(scores);print('biased-score naive counts',np.bincount(scores.argmax(axis=1),minlength=3).tolist(),'balanced row',balanced[0].round(9).tolist(),'soft column masses',balanced.sum(axis=0).round(9).tolist())
    z=np.zeros((2,2));print('collapsed loss / gradient norm',objective(z,targets(z))[0],float(np.linalg.norm(objective(z,targets(z))[1])))
swapped prediction loss 0.914840165 0.144216102 assignment mass per prototype [2.0, 2.0, 2.0] hard assignment counts [2, 2, 2]
biased-score naive counts [6, 0, 0] balanced row [0.333333333, 0.333333333, 0.333333333] soft column masses [2.0, 2.0, 2.0]
collapsed loss / gradient norm 1.0986122886681093 0.0

When the method fails

Give every example the same biased score row (2,0,0). Plain argmax assigns all six to the first prototype; balancing returns the same uniform soft row for every example. Soft masses are perfectly balanced, yet no example has a distinct code. At a zero encoder, our loss is log(3) and the encoder gradient is zero. Balancing alone therefore does not establish meaningful separation.

Hard assignment is an extra operation. Uniform soft rows can turn into identical hard labels under a deterministic tie rule. Fractional assignments can satisfy soft marginals even when B/K is not an integer; an exactly equal hard partition may be impossible. Keep those two claims separate.

DeepCluster discusses empty clusters and heavily imbalanced pseudo-labels, using reassignment and balancing strategies. SwAV’s entropy term and finite batch assignments have their own trade-offs. None guarantees clusters match the categories a downstream user wants. Monitor assignment entropy, prototype usage, held-out features and downstream quality. Deep Clustering for Unsupervised Learning of Visual Features; Unsupervised Learning of Visual Features by Contrasting Cluster Assignments

The exponential-domain implementation is deliberately bounded: it rejects excessively large score range divided by epsilon. Larger systems should use numerically stable scaling or log-domain methods rather than relying on this small example for arbitrary extreme inputs.

Exercises with answers

  1. Does equal soft mass imply equal hard argmax counts?

Answer 1: No. Identical uniform rows have equal column masses but a tie rule may choose the first prototype for every row.

  1. Can two examples have soft mass 2/3 assigned to each of three prototypes?

Answer 2: Yes: give each example probability 1/3 per prototype. An equal integer hard partition is impossible.

  1. Which target enters the gradient for view A?

Answer 3: The detached assignment from view B, not A’s own assignment.

  1. Does this program reproduce original SwAV training?

Answer 4: No. It keeps prototypes fixed, uses a tiny tanh encoder and explicit teaching temperatures/iteration counts.

Sources and next steps

Read DeepCluster Sections 3.2–3.3 for alternating pseudo-labels and degeneracies. Read SwAV’s Eqs. 2–5 for swapped targets, entropy-regularized assignments and scaling. Then compare DINO, which also matches cross-view distributions but uses a momentum teacher and centering rather than this transport constraint. Deep Clustering for Unsupervised Learning of Visual Features; Unsupervised Learning of Visual Features by Contrasting Cluster Assignments

Make a prediction, then check

All examples receive the same uniform soft assignment. What is true?

Choose one answer

Learning objectives

  • Implement entropy-smoothed balanced assignments and frozen swapped targets.
  • Distinguish soft mass, hard counts and a collapsed representation.

Prerequisites & connections

Explore related knowledge →

References

  1. Deep Clustering for Unsupervised Learning of Visual Features
    Mathilde Caron; Piotr Bojanowski; Armand Joulin; Matthijs Douze · 2018
  2. Unsupervised Learning of Visual Features by Contrasting Cluster Assignments
    Mathilde Caron; Ishan Misra; Julien Mairal; Priya Goyal; Piotr Bojanowski; Armand Joulin · 2020

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.

  • Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, executable examples and corresponding bilingual equations, code and exercises. Not independent human or second-agent review.
  • Four CPython 3.12.4 checks per chapter: spectra and exact recurrence with scale-aware tolerances, frozen ridge probes, literal graded retrieval metrics, whitening/SVD constraints, finite balancing marginals and stopped targets, pseudo-label denominator, exact noise expectation and temperature-weighted distillation as applicable, plus bilingual structure. All eight programs use NumPy 1.26.4; no real image/text benchmark reproduction claimed.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.