braindecode.training.info_nce#

braindecode.training.info_nce(z1, z2, temperature=0.1)[source]#

InfoNCE (NT-Xent) contrastive loss between two views of a batch [1].

Row i of z1 and row i of z2 embed two views of the same sample. Each of the \(2N\) rows of cat([z1, z2]) is an anchor whose positive is the other view of its sample and whose negatives are the other \(2N - 2\) rows:

\[\ell_i = -\log \frac{\exp(\mathrm{sim}(z_i, z_{i^+}) / \tau)} {\sum_{k \neq i} \exp(\mathrm{sim}(z_i, z_k) / \tau)}\]

with cosine similarity \(\mathrm{sim}\) and temperature \(\tau\). The loss is the mean of \(\ell_i\) over the \(2N\) anchors.

Parameters:
  • z1 (Tensor) – Embeddings of the two views, both of shape (batch, dim), for example model(x, return_features=True)["embedding"] passed through a projection head.

  • z2 (Tensor) – Embeddings of the two views, both of shape (batch, dim), for example model(x, return_features=True)["embedding"] passed through a projection head.

  • temperature (float) – Temperature \(\tau\) dividing the cosine similarities. Must be positive.

Returns:

The scalar loss.

Return type:

Tensor

References

[1]

Chen, T., Kornblith, S., Norouzi, M., Hinton, G. (2020). A Simple Framework for Contrastive Learning of Visual Representations. ICML. https://arxiv.org/abs/2002.05709

Examples using braindecode.training.info_nce#

Contrastive pretraining of any model with InfoNCE

Contrastive pretraining of any model with InfoNCE