SimCLR: two views, one shared encoder, all the other candidates
SimCLR
Train a small nonlinear encoder and projection head with symmetric NT-Xent, checking masks, gradients and degenerate batches.
simclrStart with the problem
Take two independently augmented views of each image, encode both with the same network, and ask each view to identify its partner among the other views in the batch. SimCLR turns this simple construction into a concrete training framework.
The original paper separates the representation used downstream from a projection used for the contrastive loss. Its candidate objective is related to InfoNCE. We implement the complete symmetric loss and backpropagation for three objects with two supplied two-dimensional views each, using a small nonlinear encoder and nonlinear projection head.
Definitions and derivation
For N underlying objects there are 2N views. We store partners in adjacent rows, so the partner map swaps rows 0↔1, 2↔3 and so on. Shared encoder f produces h; projector g produces z, then normalize each nonzero row:
Our W and V are both 2×2, giving eight trainable parameters. The original framework uses much larger networks and a different projection architecture; this tanh pair is an explicit teaching model. The downstream representation is h. The projection head is used to shape the training objective and is normally discarded for the original paper’s representation evaluation.
The normalized temperature-scaled cross-entropy excludes self but includes the positive in the denominator:
Each anchor has 2N−1 candidates: one positive and 2N−2 negatives. The symmetric average counts every view as an anchor. Excluding the positive from the denominator or including the anchor itself implements a different objective. The code uses a negative-infinity self mask, stable row softmax and the adjacent partner map.
All embeddings receive gradients both as anchors and as candidates. If p is the masked row probability matrix, differentiating the shared Gram matrix gives:
The Gᵀ term is essential: other anchors use this embedding as a candidate. The normalization derivative removes the radial component, so gradients change direction rather than directly rewarding vector scale. Backpropagate further through the projector tanh, V, encoder tanh and W. There is no detached target branch in this example.
For N=1 there is only the positive candidate. Every loss is zero and the entire encoder gradient is zero, even when the two views disagree. For a batch of identical nonzero projected vectors, loss is log(2N−1); the shared normalized model can also have zero gradient there. Negatives make the collapsed loss worse than a separating solution, but do not eliminate all collapsed stationary configurations.
Run the calculation
Complete Python 3.12 / NumPy 1.26.4 program:
import numpy as np
def views():return np.array([[1.,.1],[.8,-.1],[-.2,1],[.1,.9],[-1,-.4],[-.8,-.6]])
def objective(theta,x=None,temperature=.4):
x=views() if x is None else np.asarray(x,dtype=float);t=np.asarray(theta,dtype=float)
if t.shape!=(8,) or x.ndim!=2 or x.shape[1]!=2 or len(x)<2 or len(x)%2 or len(x)>16 or not np.isfinite(x).all() or not np.isfinite(t).all() or temperature<=0:raise ValueError('Use paired adjacent 2D views and eight finite encoder/projector parameters.')
w=t[:4].reshape(2,2);v=t[4:].reshape(2,2);h=np.tanh(x@w);raw=np.tanh(h@v);norm=np.linalg.norm(raw,axis=1,keepdims=True)
if np.any(norm<1e-10):raise ValueError('The teaching normalization requires nonzero projections.')
z=raw/norm;count=len(z);positive=np.arange(count)^1;logits=z@z.T/temperature;np.fill_diagonal(logits,-np.inf);shift=logits.max(axis=1,keepdims=True);p=np.exp(logits-shift);p/=p.sum(axis=1,keepdims=True)
loss=float(np.mean(-np.log(p[np.arange(count),positive])));g=p.copy();g[np.arange(count),positive]-=1;g/=count
gz=(g+g.T)@z/temperature;gr=(gz-z*np.sum(gz*z,axis=1,keepdims=True))/norm
pre=gr*(1-raw*raw);gv=h.T@pre;gw=x.T@((pre@v.T)*(1-h*h))
return loss,np.r_[gw.ravel(),gv.ravel()],z,p
def initial():return np.r_[np.array([[.7,.2],[-.1,1.]]).ravel(),np.array([[1.,.1],[.2,.8]]).ravel()]
if __name__=='__main__':
t=initial();start=objective(t)[0]
for _ in range(150):t-=.03*objective(t)[1]
loss,g,z,p=objective(t);print('NT-Xent before/after',round(start,9),round(loss,9),'positive probabilities',p[np.arange(6),np.arange(6)^1].round(9).tolist());print('self probabilities',np.diag(p).tolist())
one=objective(initial(),views()[:2]);print('one-object batch loss / gradient norm',one[0],float(np.linalg.norm(one[1])))
collapsed=objective(initial(),np.tile([[1.,0]],(6,1)));print('collapsed loss',round(collapsed[0],9),'log(5)',round(float(np.log(5)),9),'gradient norm',float(np.linalg.norm(collapsed[1])))
Actual output:
NT-Xent before/after 0.303506059 0.122182199 positive probabilities [0.8793017, 0.89862632, 0.878046525, 0.881512322, 0.874972932, 0.897767935]
self probabilities [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
one-object batch loss / gradient norm 0.0 0.0
collapsed loss 1.609437912 log(5) 1.609437912 gradient norm 3.7738465561416927e-17
With τ=0.4 and 150 updates, NT-Xent falls from 0.303506059 to 0.122182199. Partner probabilities become approximately 0.875–0.899, and every self probability is exactly zero. The one-object batch gives zero loss and gradient. Identical views give log 5≈1.609437912 and only rounding-level gradient.
The views are fixed supplied coordinates, not randomly resampled image crops. Training tests the loss and shared gradient paths; it does not reproduce ImageNet accuracy, augmentation ablations, global batch normalization or large-batch optimizer behavior. Constructing the dense similarity matrix costs O((2N)²d) for d-dimensional projections and stores O(N²) scores, in addition to network activations.
When the method fails
Augmentation choice defines which information partners should share. Stronger augmentation can help or erase the object; an instance-based negative may still share a semantic class with the anchor. Temperature, batch composition and the projection head should be evaluated together.
Compare representations at the same evaluation stage: using h in one experiment and z in another changes the comparison. Avoid leaking validation labels into augmentation or hyperparameter choices. A lower loss at a different batch size is not automatically a better representation, because the number and difficulty of competitors have changed.
Exercises with answers
- How many negatives does an anchor have for N objects?
Answer 1: 2N−2; the denominator has 2N−1 candidates because it includes the positive.
- Why does the embedding gradient include Gᵀ?
Answer 2: Each embedding is also a candidate for other anchors, and those paths share the same encoder parameters.
- What training signal remains with only one object?
Answer 3: None from NT-Xent: its sole candidate is always the positive.
- Which output is normally retained for the original downstream protocol?
Answer 4: The encoder representation h, after discarding the projection head g.
Sources and next steps
SimCLR physical pages 2–3 introduce encoder/projector roles, the loss and Algorithm 1; page 3 also describes large-batch and normalization conditions. CPC physical pages 3–4 supply the candidate-loss lineage. Our nonlinear eight-parameter implementation and degenerate-batch tests are original. Continue with MoCo for queued candidates and BYOL for an objective without explicit negatives.
Make a prediction, then check
Which entry must be excluded from each SimCLR denominator?
Learning objectives
- Implement symmetric masking and both embedding-gradient roles.
- Recognize the one-object and identical-view degeneracies.
Prerequisites & connections
Explore related knowledge →References
- A Simple Framework for Contrastive Learning of Visual Representations
Ting Chen; Simon Kornblith; Mohammad Norouzi; Geoffrey Hinton · 2020 - Representation Learning with Contrastive Predictive Coding — arXiv v2
Aaron van den Oord; Yazhe Li; Oriol Vinyals · 2018
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:
- A Simple Framework for Contrastive Learning of Visual Representations · Physical pages 2–3, Algorithm 1: two views, shared encoder and projection, symmetric NT-Xent, self exclusion and downstream projector removal.
- Representation Learning with Contrastive Predictive Coding — arXiv v2 · Physical pages 3–4, Section 2.3: contrastive candidate classification and InfoNCE.
Related topics