AI Wiki中文/EN

BYOL: predict a slowly moving target

BYOL

Train an online predictor against a detached EMA encoder and test both gradient correctness and a collapsed zero-loss construction.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with the problem

BYOL trains one view of an example to predict a representation of another view without explicitly contrasting it against negative examples. An online network learns through gradients; a target network follows a moving average. Only the online side has a prediction head.

The BYOL paper defines these asymmetries and reports their empirical behavior. SimSiam later studies a related design without a momentum target. We implement a small BYOL-style training loop and keep the distinction between a useful observed trajectory and a universal anti-collapse claim explicit.

Definitions and derivation

The original online pipeline contains encoder f, projector g and predictor q. The target has corresponding encoder/projector parameters ξ but no predictor:

y=fθ(v),z=gθ(y),p=qθ(z),z′=gξ(fξ(v′)),pˉ=p∥p∥,zˉ′=z′∥z′∥.y=f_\theta(v),\quad z=g_\theta(y),\quad p=q_\theta(z),\qquad z'=g_\xi(f_\xi(v')),\quad \bar p=\frac p{\|p\|},\quad\bar z'=\frac{z'}{\|z'\|}.

Two augmented views exchange roles. The normalized prediction is matched to the stopped target projection. Our convention averages the two directions; the original paper sums them, a factor of two that must be accounted for when comparing learning rates. After the online gradient update, apply EMA to matching encoder/projector parameters:

L=12E[2−2pˉ(v)⊤sg⁡(zˉ′(v′))+2−2pˉ(v′)⊤sg⁡(zˉ′(v))],ξ←mξ+(1−m)θencoder/projector.L=\tfrac12\mathbb E\left[2-2\bar p(v)^\top\operatorname{sg}(\bar z'(v'))+ 2-2\bar p(v')^\top\operatorname{sg}(\bar z'(v))\right],\qquad \xi\leftarrow m\xi+(1-m)\theta_{\rm encoder/projector}.

The predictor is trained but is not copied into the target. The target branch’s values are recomputed as its parameters evolve; stop-gradient does not mean frozen forever. It means no derivative through those target values during the current online optimization step. EMA is an explicit state update outside that derivative.

The teaching model uses a 2×2 linear encoder W, identity projector and 2×2 linear predictor P. A separate 2×2 matrix V is the target encoder. There are eight online gradient parameters and four target state values. We deliberately omit the original MLP projectors, normalization layers and image backbone. The loss still exercises the online-only predictor, normalized regression, stopped target and post-update EMA in both view directions.

For one prediction/target pair, differentiation through unit normalization gives:

∇p(2−2pˉ⊤zˉ′)=−2∥p∥[zˉ′−pˉ(pˉ⊤zˉ′)],pˉi=zˉi′=u ∀i⟹L=0.\nabla_p\big(2-2\bar p^\top\bar z'\big) =-\frac2{\|p\|}\left[\bar z'-\bar p(\bar p^\top\bar z')\right],\qquad \bar p_i=\bar z'_i=u\ \forall i\quad\Longrightarrow\quad L=0.

The first equality supplies the online prediction gradient. Its component along p is removed, as required by normalization. For finite-difference tests, hold target matrix V fixed while perturbing W or P. Perturbing the target along with the online parameters would test a different derivative. The program never adds a loss gradient to V.

The second equality is a crucial limitation: if all predictions and target projections equal the same nonzero unit vector, the objective is zero. BYOL’s training dynamics and architecture can avoid such solutions in studied settings, but the scalar objective does not forbid them. A nonzero variance in one small run is evidence about that run, not a proof that EMA or stop-gradient prevents collapse universally.

Run the calculation

Complete Python 3.12 / NumPy 1.26.4 program:

import numpy as np

X1=np.array([[1.,.1],[.2,1],[-1,-.2],[-.1,-1]])
X2=np.array([[.8,-.1],[-.1,.9],[-.9,.1],[.1,-.8]])


def normalize(x):
    norm=np.linalg.norm(x,axis=1,keepdims=True)
    if np.any(norm<1e-10):raise ValueError('Nonzero vectors are required for this exact normalization.')
    return x/norm,norm


def objective(theta,target_weight):
    w=theta[:4].reshape(2,2);p=theta[4:].reshape(2,2);loss=0.;gw=np.zeros_like(w);gp=np.zeros_like(p)
    for x,target_input in ((X1,X2),(X2,X1)):
        h=x@w;prediction=h@p;pn,norm=normalize(prediction);tn,_=normalize(target_input@target_weight);dot=np.sum(pn*tn,axis=1,keepdims=True)
        loss+=float(np.mean(2-2*dot))/2;gradient=-(tn-pn*dot)/(len(x)*norm);gp+=h.T@gradient;gw+=x.T@gradient@p.T
    return loss,np.r_[gw.ravel(),gp.ravel()]


def initial():return np.r_[np.array([[1.,.2],[-.3,.7]]).ravel(),np.array([[.7,-.1],[.2,1.1]]).ravel()]


if __name__=='__main__':
    theta=initial();target=theta[:4].reshape(2,2).copy();start=objective(theta,target)[0]
    for _ in range(100):
        loss,gradient=objective(theta,target);theta-=.05*gradient;target=.9*target+.1*theta[:4].reshape(2,2)
    print('BYOL-style loss before/after',round(start,9),round(objective(theta,target)[0],9),'encoder / EMA lag',round(float(np.linalg.norm(theta[:4].reshape(2,2)-target)),9))
    embedding=X1@theta[:4].reshape(2,2);print('online feature variances',embedding.var(axis=0).round(9).tolist())
    constant=np.tile([[1.,0]],(4,1));unit,_=normalize(constant);print('constant matched representation loss',float(np.mean(2-2*np.sum(unit*unit,axis=1))))

Actual output:

BYOL-style loss before/after 0.119427982 0.0390504 encoder / EMA lag 0.020057831
online feature variances [0.513682107, 0.138537972]
constant matched representation loss 0.0

One hundred updates at step size 0.05 with m=0.9 reduce the mean two-direction loss from 0.119427982 to 0.039050400. Online feature variances are about 0.51368 and 0.13854, while the encoder/EMA lag is about 0.02006. Matching constant nonzero vectors gives exactly zero loss in the separate construction.

The views are fixed small arrays, and the learned features are not evaluated on a downstream dataset. Identity projection and linear prediction make the state updates inspectable; they do not reproduce the original backbone, augmentation or optimizer ablations. Online and target forward passes both cost compute, while only the online path retains the gradient graph. EMA costs linear work in the matching parameter count.

When the method fails

Successful learning depends on interactions among augmentations, predictor, normalization, optimization and target updates. A simplistic explanation that one component alone guarantees success goes beyond the experiment. Constant inputs cannot yield diverse deterministic representations merely by adding stop-gradient.

Keep target updates and online optimizer steps separate in implementation and checkpoint both states for exact resumption. Monitor representation variance and dimensional rank along with loss, and evaluate the retained encoder rather than assuming a small regression loss implies useful semantics.

Exercises with answers

  1. Does the target network have the online predictor?

Answer 1: No. EMA applies to corresponding encoder/projector parameters, not the predictor.

  1. What is held fixed in an online finite-difference gradient check?

Answer 2: The current target parameters and therefore target values.

  1. Can a constant representation achieve zero regression loss?

Answer 3: Yes, if normalized predictions and targets are the same nonzero constant vector.

  1. Why save the target state when resuming training?

Answer 4: Its EMA history is not recoverable from the current online weights alone.

Sources and next steps

BYOL physical pages 3–4, Equations 1–3, define online/target pipelines, normalized regression, symmetric loss and post-step EMA. SimSiam physical page 2 contrasts this design with a shared encoder and stop-gradient without EMA. The small linear dynamics and collapse construction are original. Continue with SimSiam and Barlow Twins for different no-negative objectives.

Make a prediction, then check

Does zero BYOL-style loss alone rule out collapse?

Choose one answer

Learning objectives

  • Separate gradient-updated online parameters from EMA target state.
  • Test a stop-gradient derivative without moving the target.

Prerequisites & connections

Explore related knowledge →

References

  1. Bootstrap Your Own Latent: A New Approach to Self-Supervised Learning — arXiv v3
    Jean-Bastien Grill; Florian Strub; Florent Altché; Corentin Tallec; Pierre H. Richemond; Elena Buchatskaya; Carl Doersch; Bernardo Avila Pires; Zhaohan Daniel Guo; Mohammad Gheshlaghi Azar; Bilal Piot; Koray Kavukcuoglu; Rémi Munos; Michal Valko · 2020
  2. Exploring Simple Siamese Representation Learning
    Xinlei Chen; Kaiming He · 2021

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.

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.