AI Wiki中文/EN

MoCo: keep a queue, let the key encoder move slowly

MoCo

Execute two queue-based contrastive steps with detached keys, a momentum encoder and an explicit FIFO update order.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with the problem

A large set of negative candidates can be useful without placing every candidate’s image in the current training batch. MoCo stores previously encoded keys in a queue. The difficulty is consistency: old keys were produced by older parameters, so a rapidly changing key encoder can make the dictionary unstable.

Momentum Contrast addresses this with a slowly updated key encoder. Its classification loss follows the candidate structure introduced in CPC. We run the queue and parameter updates explicitly on two-dimensional examples, including the state left behind for the next step.

Definitions and derivation

Each current object supplies a query view and a key view. Normalize query and positive key, then compare the query against its positive and the stored queue Q:

q=norm⁡(fθq(xq)),k+=sg⁡(norm⁡(fθk(xk))),ℓ=−log⁡eq⊤k+/τeq⊤k+/τ+∑k∈Qeq⊤k/τ.q=\operatorname{norm}(f_{\theta_q}(x_q)),\quad k^+=\operatorname{sg}(\operatorname{norm}(f_{\theta_k}(x_k))),\qquad \ell=-\log\frac{e^{q^\top k^+/\tau}}{e^{q^\top k^+/\tau}+\sum_{k\in Q}e^{q^\top k/\tau}}.

The stop-gradient operator sg preserves the key’s value but prevents the current loss from updating its encoder through that path. Queue entries are also constants in the current backward pass. If Q has K entries, there are K+1 candidates. Keys in the queue are stored vectors, not raw examples automatically re-encoded at every step.

Our implementation follows the paper’s Algorithm 1 ordering: compute current keys with the current key encoder; compute loss against the old queue; update query weights by gradient descent; then update key weights by exponential moving average and enqueue the already computed keys:

θqnew=θq−η∇θqL,θknew=mθk+(1−m)θqnew,Qnew=FIFO⁡(Q,k1:B+).\theta_q^{\rm new}=\theta_q-\eta\nabla_{\theta_q}L,\qquad \theta_k^{\rm new}=m\theta_k+(1-m)\theta_q^{\rm new},\qquad Q^{\rm new}=\operatorname{FIFO}(Q,k^+_{1:B}).

The FIFO operation discards the earliest B entries and appends the B current keys, keeping queue size fixed. Inserting current positives before computing the loss can make those same vectors also act as negatives. Updating the key weights after the query step does not retroactively change the keys already produced for this batch.

Unroll the moving average to see what momentum means:

θk,t=mtθk,0+(1−m)∑s=1tmt−sθq,s.\theta_{k,t}=m^t\theta_{k,0}+(1-m)\sum_{s=1}^{t}m^{t-s}\theta_{q,s}.

Here θq,s denotes the query weights after update s. At m=0, the next key weights copy the updated query weights; at m=1, key weights remain frozen. Intermediate m smooths parameter changes. This is not optimizer momentum, nor an average of every individual sample’s stored embedding. The queue still contains keys from different historical encoders; EMA reduces drift rather than making all keys contemporaneous.

Only query weights receive the current gradient. Differentiate the normalized query and dot-product softmax while holding current positive and queued keys fixed. The example checks all four linear query parameters against independent finite differences of exactly that frozen-key objective. The key encoder has a state update, not a second loss gradient.

Run the calculation

Complete Python 3.12 / NumPy 1.26.4 program:

import numpy as np


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


def query_objective(weight,x,positive,queue,temperature=.3):
    q,norm=normalize(x@weight);keys=np.concatenate([positive[:,None,:],np.broadcast_to(queue,(len(x),*queue.shape))],axis=1);logits=np.einsum('nd,nkd->nk',q,keys)/temperature;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[:,0])));gq=(np.einsum('nk,nkd->nd',p,keys)-positive)/(temperature*len(x));gr=(gq-q*np.sum(gq*q,axis=1,keepdims=True))/norm
    return loss,x.T@gr


def step(query_weight,key_weight,queue,xq,xk,momentum=.9,rate=.05):
    if not 0<=momentum<=1 or rate<0 or len(queue)<len(xq):raise ValueError('Use valid EMA/rate and a queue at least as large as the batch.')
    positive,_=normalize(xk@key_weight);loss,gradient=query_objective(query_weight,xq,positive,queue)
    next_query=query_weight-rate*gradient
    next_key=momentum*key_weight+(1-momentum)*next_query
    next_queue=np.concatenate([queue[len(xq):],positive],axis=0)
    return next_query,next_key,next_queue,loss,positive


def initial():
    w=np.array([[1.,.2],[-.1,.8]]);queue=np.array([[1.,0],[0,1],[-1,0],[0,-1]]);xq=np.array([[1.,.1],[-.2,1]]);xk=np.array([[.9,-.1],[.1,.9]])
    return w,w.copy(),queue,xq,xk


if __name__=='__main__':
    w,v,queue,xq,xk=initial()
    for i in range(2):
        old=w.copy();w,v,queue,loss,positive=step(w,v,queue,xq,xk);print('step',i+1,'loss',round(loss,9),'encoder lag',round(float(np.linalg.norm(w-v)),9),'queue',queue.round(6).tolist())
    print('query / key encoder',w.round(9).tolist(),v.round(9).tolist())

Actual output:

step 1 loss 0.746128331 encoder lag 0.009019133 queue [[-1.0, 0.0], [0.0, -1.0], [0.994016, 0.109233], [0.013512, 0.999909]]
step 2 loss 0.76160218 encoder lag 0.016364638 queue [[0.994016, 0.109233], [0.013512, 0.999909], [0.994023, 0.109175], [0.014591, 0.999894]]
query / key encoder [[0.9975192, 0.195284753], [-0.082716125, 0.806330916]] [[0.999581979, 0.199482698], [-0.097449551, 0.80095972]]

The queue has four rows and the batch has two. After step one, the oldest two rows are gone and the current two normalized keys occupy the end. After step two, every original queue row has been replaced. Query/key lag is about 0.009019133 and then 0.016364638 with m=0.9.

Loss rises from 0.746128331 to 0.761602180 between these steps. The denominator now contains different keys, including keys of the same recurring synthetic objects, so these are different objectives. The increase does not by itself diagnose a bad gradient update. No downstream accuracy is measured.

The model uses fixed supplied views, linear encoders and a tiny queue. It does not implement the original image backbone, distributed batch shuffling or training schedule. Queue storage is O(Kd); comparing B queries with K stored d-dimensional keys costs O(BKd), plus current encoder work. Old keys need no current activation graph.

When the method fails

A queue can contain semantic false negatives or repeated identities. Very old keys can become stale, while excessive encoder smoothing can slow adaptation. Queue size and momentum are coupled design choices, not independent promises of quality.

Check update order, normalization, queue replacement and whether gradients leak into the key branch before interpreting a training run. Compare evaluation features from the intended encoder and use matched data and budgets when contrasting MoCo with in-batch methods.

Exercises with answers

  1. Are queued vectors recomputed with the newest encoder each step?

Answer 1: No. They retain their stored historical values until FIFO replacement.

  1. Which weights receive the current loss gradient?

Answer 2: Query encoder weights; the key encoder is updated by EMA.

  1. Why can successive losses increase even with a correct query gradient?

Answer 3: The queue changes, so the candidate set and objective change between steps.

  1. What does m=0 do after the query update?

Answer 4: It copies the updated query weights into the next key encoder; already computed keys stay unchanged.

Sources and next steps

MoCo physical pages 3–4 describe the queue and momentum encoder; page 4 Algorithm 1 fixes the ordering used here. CPC physical pages 3–4 provide candidate-loss context. The exact queue trace and gradient checks are original. Continue with SimCLR to compare in-batch keys, or BYOL to see EMA without a negative queue.

Make a prediction, then check

How are MoCo key-encoder parameters updated in this example?

Choose one answer

Learning objectives

  • Execute FIFO and EMA in a stated order.
  • Check query gradients with keys held constant.

Prerequisites & connections

Explore related knowledge →

References

  1. Momentum Contrast for Unsupervised Visual Representation Learning
    Kaiming He; Haoqi Fan; Yuxin Wu; Saining Xie; Ross Girshick · 2020
  2. 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

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