AI Wiki中文/EN

Barlow Twins: match features without repeating the same one

Barlow Twins

Train a shared linear map with cross-correlation loss, differentiate batch normalization and test constant and rank-limited batches.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with the problem

Two views should agree about the same feature, but different feature coordinates should not all repeat the same signal. Barlow Twins expresses these goals with a cross-correlation matrix between view embeddings across the batch, rather than explicit negative pairs.

The original paper penalizes diagonal mismatch and off-diagonal redundancy. VICReg later separates invariance, variance preservation and covariance regularization. We calculate the Barlow Twins objective and its complete gradient, including the normalization that makes a constant batch a subtle case.

Definitions and derivation

A and B contain N corresponding view embeddings as rows and d feature coordinates as columns. Center and standardize each feature over the batch, not each example over its features:

ZniA=Ani−μiAN−1∑n(Ani−μiA)2+ϵ,C=1N(ZA)⊤ZB.Z^A_{ni}=\frac{A_{ni}-\mu_i^A}{\sqrt{N^{-1}\sum_n(A_{ni}-\mu_i^A)^2+\epsilon}},\qquad C=\frac1N(Z^A)^\top Z^B.

Our implementation uses population variance with denominator N and ε=10⁻⁸. State these conventions explicitly: using a sample standard deviation with denominator N−1 while still dividing the correlation by N introduces a scale mismatch. With ε>0, even identical finite-variance columns have diagonal correlation slightly below one; the stabilizer avoids dividing by zero but slightly changes exact scale invariance.

The d×d cross-correlation objective is:

L=∑i(1−Cii)2+λ∑i≠jCij2,λ>0.L=\sum_i(1-C_{ii})^2+\lambda\sum_{i\ne j}C_{ij}^2,\qquad \lambda>0.

The diagonal term encourages matching corresponding coordinates across views. The off-diagonal term discourages different coordinates from carrying the same correlated signal. Zero correlation is not full statistical independence: nonlinear dependencies can remain. In the ideal unstabilized case, C=I means aligned standardized views with mutually uncorrelated coordinates, not necessarily disentangled causal factors.

Differentiate the weighted matrix error, then propagate to both normalized views:

Gii=2(Cii−1),Gij=2λCij (i≠j),∇ZAL=1NZBG⊤,∇ZBL=1NZAG.G_{ii}=2(C_{ii}-1),\quad G_{ij}=2\lambda C_{ij}\ (i\ne j),\qquad \nabla_{Z^A}L=\frac1NZ^BG^\top,\quad \nabla_{Z^B}L=\frac1NZ^AG.

For each standardized column z with scale s, backpropagation through centering and variance uses (g−mean(g)−z·mean(g·z))/s. Holding batch means or scales fixed would omit necessary terms. Both view branches receive gradients; there is no stop-gradient, EMA encoder or negative queue in this calculation.

Centering gives each view matrix rank at most N−1, so the cross-correlation rank is at most min(d,N−1). If d exceeds N−1, C cannot equal the d-dimensional identity. This is a finite-batch rank limitation, not a claim that large-dimensional Barlow Twins cannot train. Its loss can still be optimized across batches and parameter updates.

A constant column is also important. With our ε stabilizer its normalized values are zero. If all columns are constant, C=0 and loss is d, yet both embedding gradients are zero because they multiply zero normalized views. The objective penalizes collapse, but this implementation still has a collapsed stationary point. Penalizing a bad solution does not prove every optimizer escapes it.

Actual cross-correlations before and after training the shared linear map. Both panels use the same −1 to +1 color scale. The final matrix is near identity, not exactly identity; epsilon stabilization and finite optimization remain.
Actual cross-correlations before and after training the shared linear map. Both panels use the same −1 to +1 color scale. The final matrix is near identity, not exactly identity; epsilon stabilization and finite optimization remain.

Run the calculation

Complete Python 3.12 / NumPy 1.26.4 program:

import numpy as np


def standardize(x,epsilon=1e-8):
    centered=x-x.mean(axis=0);std=np.sqrt(np.mean(centered**2,axis=0)+epsilon);return centered/std,std


def loss_gradient(a,b,weight=.1):
    a,b=np.asarray(a,dtype=float),np.asarray(b,dtype=float)
    if a.ndim!=2 or a.shape!=b.shape or len(a)<2 or not np.isfinite(a).all() or not np.isfinite(b).all() or weight<0:raise ValueError('Use matching finite view matrices and nonnegative off-diagonal weight.')
    za,sa=standardize(a);zb,sb=standardize(b);n=len(a);corr=za.T@zb/n;error=corr-np.eye(corr.shape[0]);scale=np.full_like(corr,weight);np.fill_diagonal(scale,1);loss=float(np.sum(scale*error**2));gc=2*scale*error;ga=zb@gc.T/n;gb=za@gc/n
    ga=(ga-ga.mean(axis=0)-za*np.mean(ga*za,axis=0))/sa;gb=(gb-gb.mean(axis=0)-zb*np.mean(gb*zb,axis=0))/sb
    return loss,ga,gb,corr


def views():
    a=np.array([[1.,1,1],[1,-1,-1],[-1,1,-1],[-1,-1,1]])
    return a,a*np.array([2.,1.,.5])+[.1,0,.3]


if __name__=='__main__':
    a,b=views();w=np.array([[1.,.3,0],[.1,1,.2],[.3,-.1,1]]);start=loss_gradient(a@w,b@w)[0]
    for _ in range(400):
        loss,ga,gb,c=loss_gradient(a@w,b@w);w-=.1*(a.T@ga+b.T@gb)
    end,ga,gb,c=loss_gradient(a@w,b@w);print('redundancy loss before/after',round(start,9),round(end,9),'cross-correlation',c.round(6).tolist())
    constant=np.ones((4,3));loss,ga,gb,c=loss_gradient(constant,constant);print('constant loss',loss,'gradient norms',float(np.linalg.norm(ga)),float(np.linalg.norm(gb)))
    small=np.array([[1.,2,3],[-1,-2,-3]]);loss,ga,gb,c=loss_gradient(small,small);print('two-row three-feature correlation rank',np.linalg.matrix_rank(c),'loss',round(loss,9))

Actual output:

redundancy loss before/after 0.062171597 8.752e-05 cross-correlation [[0.994479, -0.000213, 0.003959], [-0.000107, 0.99701, -0.001129], [0.001015, -0.000576, 0.993198]]
constant loss 3.0 gradient norms 0.0 0.0
two-row three-feature correlation rank 1 loss 0.599999995

Four supplied three-dimensional views are paired by known feature scaling and offsets. A shared 3×3 linear map is trained for 400 updates with λ=0.1. Loss falls from 0.062171597 to about 8.752×10⁻⁵; the final correlation is close to identity but not equal. This is an actual nine-parameter optimization, not a static diagram of an ideal matrix.

For a constant 4×3 batch the loss is three and both gradients are zero. A two-row, three-feature batch has correlation rank one and loss about 0.6, illustrating the rank constraint. These diagnostic cases are not a reproduction of image-backbone performance or the original high-dimensional projection network.

Cross-correlation requires O(Nd²) work and O(d²) matrix storage, plus embeddings and network activations. In distributed training, the intended batch statistics and cross-products need correctly aggregated sample counts; local and global normalization define different computations.

When the method fails

Redundancy reduction depends on the chosen coordinates and second-order statistic. It does not ensure every feature is meaningful, and numerical stabilization affects very low-variance dimensions. Inspect diagonal values, off-diagonal magnitude and feature variances rather than reporting only the total loss.

VICReg adds an explicit variance-preservation term and uses within-view covariance penalties, so it is not simply another name for this cross-correlation objective. Compare methods under matched augmentation and evaluation protocols. Low self-supervised loss remains separate from demonstrated downstream usefulness.

Exercises with answers

  1. Which dimension is used to standardize features?

Answer 1: The batch dimension: each feature column is centered and scaled across examples.

  1. Why can C not equal I when d>N−1?

Answer 2: Centered view matrices have rank at most N−1, so their cross-product cannot have full rank d.

  1. Does zero cross-correlation imply independence?

Answer 3: No. It constrains second-order relationships, not every nonlinear dependency.

  1. Why are gradients zero for constant stabilized views?

Answer 4: Centering makes both normalized views zero, and the correlation gradients multiply those zero matrices.

Sources and next steps

Barlow Twins physical pages 2–3, Equations 1–2 and Algorithm 1, define normalized cross-correlation and its diagonal/off-diagonal objective. VICReg physical page 4 explicitly contrasts its variance and covariance design with Barlow Twins. The shared linear experiment, full normalization derivatives and rank/constant counterexamples are original. Compare SimSiam, BYOL and contrastive learning.

Make a prediction, then check

What does the constant-batch example demonstrate?

Choose one answer

Learning objectives

  • Differentiate cross-correlation through batch standardization.
  • Diagnose rank and constant-feature limitations.

Prerequisites & connections

Explore related knowledge →

References

  1. Barlow Twins: Self-Supervised Learning via Redundancy Reduction
    Jure Zbontar; Li Jing; Ishan Misra; Yann LeCun; Stéphane Deny · 2021
  2. VICReg: Variance-Invariance-Covariance Regularization for Self-Supervised Learning — arXiv v3
    Adrien Bardes; Jean Ponce; Yann LeCun · 2022

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, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
  • Four focused CPython 3.12.4 checks passed per chapter: independent finite differences, exact covariance/binomial references, queue transitions, stopped versus full gradients, batch-normalization derivatives and collapse/rank counterexamples as applicable. All ten programs use NumPy 1.26.4. This scoped final record supersedes the generic carried-over checklist in the frozen metadata; original drafts are retained.
  • 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.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
  • Bilingual Matplotlib 3.9.1 charts use executed article functions: exact denoising scales, binomial expected InfoNCE bounds and actual trained cross-correlations. Both locale SVGs and samples are hash-bound. Variance, expectation, shared color scales and finite-optimization limits are explicit.

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.