SimSiam: the same value can have a different training gradient
SimSiam
Compare stopped-target and full gradients at identical parameters, train a shared Siamese encoder and test constant solutions.
simsiamStart with the problem
SimSiam matches predictions between two views with a shared encoder and a predictor, without a negative queue or a separate momentum encoder. Its distinctive operation is stopping the gradient through the target of each directional comparison.
Chen and He show that this design can learn useful representations in their studied training setup. It is related to BYOL, but shares current encoder weights instead of maintaining an EMA target. We make the backward-pass distinction visible by computing two gradients for exactly the same forward loss.
Definitions and derivation
Both views pass through the same encoder/projector f and predictor q. Use negative cosine similarity between a prediction and the other view’s projection:
The paper’s f includes a backbone and projection MLP. In our teaching model f is one linear 2×2 encoder with identity projector, and q is a linear 2×2 predictor. There are eight shared trainable parameters. The original normalization layers and image network are not reproduced.
The loss averages two directed comparisons, each with a stopped target:
Stopping z₂ as the target of the first term does not freeze view 2 everywhere. The second term still propagates through p₂ and hence z₂. Both views receive prediction-path gradients through the same encoder weights. There is no separate target parameter state to update; target values are recomputed using current weights at the next step.
For nonzero vectors, the ordinary cosine derivatives are:
The stopped loss keeps the prediction derivative and discards the corresponding target derivative in each direction. A fully differentiated comparison includes both. Their forward values are identical because sg is identity in the forward pass, yet the training update differs. Thus naïvely finite-differencing the recomputed full scalar function would test the full derivative, not the stopped update.
To verify the stopped gradient, first cache the current z₁,z₂ target values, then hold those arrays fixed while perturbing encoder and predictor parameters. We separately verify the full gradient while allowing targets to change. This tests both the chain rule and the intended gradient barrier, instead of treating a loss value as proof that the backward graph is correct.
Equal normalized prediction and target vectors achieve D=−1. If every example produces the same such vector, the objective is also minimized. The original paper’s noncollapse results concern the complete training system, including architectural and optimization details; stop-gradient alone does not mathematically forbid constant solutions.
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 cosine_loss(a,b):
na=np.linalg.norm(a,axis=1,keepdims=True);nb=np.linalg.norm(b,axis=1,keepdims=True)
if np.any(na<1e-10) or np.any(nb<1e-10):raise ValueError('Nonzero representations are required.')
ua=a/na;ub=b/nb;dot=np.sum(ua*ub,axis=1,keepdims=True);n=len(a)
return -float(dot.mean()),-(ub-ua*dot)/(n*na),-(ua-ub*dot)/(n*nb)
def objective(theta,stop=True,frozen=None):
w=theta[:4].reshape(2,2);p=theta[4:].reshape(2,2);z1=X1@w;z2=X2@w;targets=(z1,z2) if frozen is None else frozen;loss=0.;gw=np.zeros_like(w);gp=np.zeros_like(p)
for x,z,target_input,target in ((X1,z1,X2,targets[1]),(X2,z2,X1,targets[0])):
value,gpred,gtarget=cosine_loss(z@p,target);loss+=value/2;gw+=x.T@gpred@p.T/2;gp+=z.T@gpred/2
if not stop and frozen is None:gw+=target_input.T@gtarget/2
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__':
t=initial();ls,gs=objective(t);lf,gf=objective(t,False);print('same stop/full loss',round(ls,9),round(lf,9),'gradient difference',round(float(np.linalg.norm(gs-gf)),9))
for _ in range(100):t-=.05*objective(t)[1]
print('stop-gradient training loss',round(objective(t)[0],9),'feature variances',(X1@t[:4].reshape(2,2)).var(axis=0).round(9).tolist())
constant=np.tile([[1.,0]],(4,1));print('matched constant negative cosine loss',cosine_loss(constant,constant)[0])
Actual output:
same stop/full loss -0.940286009 -0.940286009 gradient difference 0.178216313
stop-gradient training loss -0.977444965 feature variances [0.509306487, 0.154763396]
matched constant negative cosine loss -1.0
At initialization, stopped and full losses are both −0.940286009, but their parameter gradients differ in norm by 0.178216313. One hundred stopped-gradient updates produce loss −0.977444965, with two feature variances around 0.50931 and 0.15476. The separate matched-constant construction gives −1, demonstrating why the loss alone does not certify diversity.
These fixed two-dimensional views illustrate the update rule and do not establish image-representation quality. Both view encodings and predictions are computed each step. Stopping the target derivative removes a backward path, not its forward computation. Memory and work still depend on the network, batch size and normalization implementation.
When the method fails
A predictor, stop-gradient and normalization interact with the data and optimizer. Removing or altering one component may change behavior, but a successful small run cannot rank their importance for every architecture. Report the complete setup when comparing variants.
Cosine similarity requires a convention for zero norms; this reference rejects near-zero rows rather than silently assigning an arbitrary direction. Monitor per-dimension variance and effective rank, preserve preprocessing and architecture in checkpoints, and evaluate downstream features using a declared frozen or fine-tuned protocol.
Exercises with answers
- Does stopping z₂ in the first term freeze the second view completely?
Answer 1: No. The second directional term still backpropagates through p₂ and the shared encoder.
- Why can forward losses match while gradients differ?
Answer 2: Stop-gradient is identity for values but suppresses a chosen backward path.
- What must be frozen when finite-differencing the stopped update?
Answer 3: The target projection arrays from the unperturbed parameter state.
- Does loss −1 certify a useful representation?
Answer 4: No. Matched constant vectors also attain −1.
Sources and next steps
SimSiam physical pages 2–3, Algorithm 1 and the method discussion, define symmetric stopped cosine loss and distinguish prediction and target roles. BYOL physical pages 3–4 specify the contrasting EMA target. Our explicit stopped/full gradient comparison is an original calculation. Continue with BYOL and Barlow Twins to compare target-state and cross-correlation approaches.
Make a prediction, then check
How should the stopped SimSiam gradient be checked with finite differences?
Learning objectives
- Verify the exact target gradient barrier in both directions.
- Distinguish forward loss equality from gradient equality.
Prerequisites & connections
Explore related knowledge →References
- Exploring Simple Siamese Representation Learning
Xinlei Chen; Kaiming He · 2021 - 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
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:
- Exploring Simple Siamese Representation Learning · Physical pages 2–3, Algorithm 1: shared encoder/projector, predictor, symmetric negative cosine, detached target and gradient in the opposite direction.
- Bootstrap Your Own Latent: A New Approach to Self-Supervised Learning — arXiv v3 · Physical pages 3–4, Equations 1–3: EMA target and predictor asymmetry contrasted with SimSiam.
Related topics