Deep-learning architectures, generative models, and self-supervision · Self-supervised representation learning · DNN067 · Training method
Momentum contrast (MoCo)
MoCo maintains a queue of negative embeddings and a slowly updated key encoder, making a large contrastive dictionary available without a very large current batch. Query and key encoders follow different update rules.
In CodeSplash
Documented in the Academy only. There's no Set up button.
- Availability
- Explained here
- Code example
- Component demo, not a trained model
- Who ran it
- CodeSplash's run and the reference's record
- CodeSplash's run
- The reference's example ran in Python and R here, and they agree.
- The reference's record
- Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.
Purpose
MoCo maintains a queue of negative embeddings and a slowly updated key encoder, making a large contrastive dictionary available without a very large current batch. Query and key encoders follow different update rules.
Question / hypotheses
The operative question is whether the stated learning or sampling objective yields a useful representation or generative distribution. It is not a null-hypothesis test. Compare held-out behavior and uncertainty across data splits or independent seeds; do not turn a training loss into a p-value.
Architecture / computational structure
A gradient-updated query encoder and averaged key encoder share a queued embedding dictionary.
Assumptions
A long queue contains stale representations; too-fast key changes make comparisons inconsistent. Negatives may share semantic classes, and distributed queue management can silently duplicate or misalign positives.
Formula / computational definition
updates key parameters, while an InfoNCE loss compares each query with its positive key and queued negatives. Old keys are removed as new keys enter the queue.
Parameters and notation
Learned or estimated quantities: Query/projector parameters and moving-average key copies; queue contents are state, not free parameters.
Hyperparameters and configuration: Momentum m, queue length, temperature, augmentation, encoder/projector, batch size, and queue update order. Select these on validation data. Capacity controls representation flexibility and memory; loss weights change the optimization tradeoff; sampling/solver settings change numerical cost and approximation error where applicable. Symbols specific to this method are defined beside its formula.
Fitting, fine-tuning, and adaptation
Pretrain using the exact view/target construction and gradient-flow rules. For a new labeled task, first freeze the encoder and fit a linear or small task head, then optionally unfreeze upper layers with a smaller encoder learning rate. Usually discard the pretraining-only predictor/projector unless the downstream protocol explicitly uses it. Tune on validation tasks without leaking the final test set; monitor embedding variance and retained source transfer to detect collapse or forgetting.
How to use and calibrate
Define the data unit and deployment target; split by the independent entity, time, graph or source as appropriate before preprocessing. Fit transformations on training data and retain a locked test set. Compare transfer/linear-probe accuracy, memory cost, and queue/momentum sensitivity; verify sample identity and temporal ordering in the dictionary.
Example application
Pretrain contrastive features with a modest current batch size. This is an illustrative study design, not a claim of validated performance on a supplied dataset.
Interpretation / pitfalls
Watch out
Interpret performance against the stated use case, data split and baseline. Compare transfer/linear-probe accuracy, memory cost, and queue/momentum sensitivity; verify sample identity and temporal ordering in the dictionary. The component code below verifies only its declared local computation; passing it does not establish convergence, reproduction of a paper, or downstream scientific validity.
Python and R code examples
Scope: MoCo momentum-key update and a positive-plus-queue contrastive loss. Use the shared setup above. Dependencies: NumPy for Python; base R for R. Validation: Python executed successfully; R reviewed but unexecuted.
Full implementation route: Python/R: custom contrastive queue and non-gradient key update in PyTorch/native torch. The examples show the momentum parameter update and a fixed-dictionary contrastive loss; full training must stop gradients through keys.
Python and R
The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.
Component demo, not a trained model — MoCo momentum-key update and a positive-plus-queue contrastive loss. Use the shared setup above.
Shared setup for this chapter
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-np.asarray(x)))
def sm(x):
z = np.asarray(x); e = np.exp(z-z.max(axis=-1, keepdims=True))
return e/e.sum(axis=-1, keepdims=True)
def unit(x):
x = np.asarray(x); return x/np.maximum(np.linalg.norm(x,axis=-1,keepdims=True),1e-12)
def ln(x):
x=np.asarray(x); return (x-x.mean(axis=-1,keepdims=True))/np.sqrt(x.var(axis=-1,keepdims=True)+1e-5)
def conv2(x,k,pad=0):
x=np.pad(np.asarray(x,dtype=float),pad); k=np.asarray(k)
return np.array([[np.sum(x[i:i+k.shape[0],j:j+k.shape[1]]*k)
for j in range(x.shape[1]-k.shape[1]+1)] for i in range(x.shape[0]-k.shape[0]+1)])
def pool2(x):
return np.array([[x[i:i+2,j:j+2].mean() for j in range(0,x.shape[1]-1,2)]
for i in range(0,x.shape[0]-1,2)])
theta_q=np.array([.8,.2]); theta_k=np.array([.6,.3]); momentum=.99
theta_k=momentum*theta_k+(1-momentum)*theta_q
query=unit(theta_q); keys=unit(np.array([[.7,.3],[-.5,.2],[.1,-.8]]))
loss=-np.log(sm(keys@query/.2)[0])
print(theta_k,loss)
Component demo, not a trained model — MoCo momentum-key update and a positive-plus-queue contrastive loss. Use the shared setup above.
Shared setup for this chapter
relu <- function(x) pmax(x,0)
sigmoid <- function(x) 1/(1+exp(-x))
sm <- function(x) {
if (is.null(dim(x))) { e <- exp(x-max(x)); return(e/sum(e)) }
t(apply(x,1,function(v) { e <- exp(v-max(v)); e/sum(e) }))
}
unit <- function(x) {
if (is.null(dim(x))) return(x/max(sqrt(sum(x*x)),1e-12))
x/pmax(sqrt(rowSums(x*x)),1e-12)
}
ln <- function(x) {
if (is.null(dim(x))) return((x-mean(x))/sqrt(mean((x-mean(x))^2)+1e-5))
d <- x-rowMeans(x); d/sqrt(rowMeans(d*d)+1e-5)
}
conv2 <- function(x,k,pad=0L) {
if(pad>0) { z<-matrix(0,nrow(x)+2*pad,ncol(x)+2*pad)
z[(pad+1):(pad+nrow(x)),(pad+1):(pad+ncol(x))]<-x; x<-z }
out<-matrix(0,nrow(x)-nrow(k)+1,ncol(x)-ncol(k)+1)
for(i in seq_len(nrow(out))) for(j in seq_len(ncol(out)))
out[i,j]<-sum(x[i:(i+nrow(k)-1),j:(j+ncol(k)-1),drop=FALSE]*k)
out
}
pool2 <- function(x) {
out<-matrix(0,nrow(x)%/%2,ncol(x)%/%2)
for(i in seq_len(nrow(out))) for(j in seq_len(ncol(out)))
out[i,j]<-mean(x[(2*i-1):(2*i),(2*j-1):(2*j)])
out
}
theta_q<-c(.8,.2); theta_k<-c(.6,.3); momentum<-.99
theta_k<-momentum*theta_k+(1-momentum)*theta_q
query<-unit(theta_q); keys<-unit(matrix(c(.7,.3,-.5,.2,.1,-.8),3,byrow=TRUE))
loss<--log(sm(as.vector(keys%*%query)/.2)[1]); print(list(key=theta_k,loss=loss))
Sources
- Original research / author referencearxiv.org
From the CodeSplash reference, entry DNN067.