Skip to content

Contrastive learning: CPC, SimCLR and MoCo

Learn representations by picking the right partner out of a crowd. CPC predicts the future, SimCLR matches two views of a row against the batch, and MoCo keeps a queue of keys from a slow encoder. Then check what was learned.

Advanced ~15 min11 steps

What runs in CodeSplash

You will be able to

  • Write the InfoNCE loss as classification of the positive among candidates
  • Explain how SimCLR builds positives and negatives, and the role of temperature
  • Describe MoCo's momentum encoder and queue
  • Check a learned representation with a probe, alignment and uniformity, and collapse

Read first

01

Find your partner

Read

Contrastive learningContrastive learningLearning representations without labels by pulling two views of the same row together and pushing other rows' views away. learns without labels by making each example pick its partner out of a crowd. Give an anchor qq, one positive k+k^+ and several negatives, score each by similarity, and treat it as classification. That is the InfoNCE lossInfoNCE lossA loss that asks each row to pick out its own corrupted view among the views of every row in the batch.:

L=−log⁡exp⁡(q⋅k+/τ)∑jexp⁡(q⋅kj/τ).L = -\log \frac{\exp(q \cdot k^+ / \tau)}{\sum_{j} \exp(q \cdot k_j / \tau)} .

The temperature τ\tau sets how sharply near misses are punished. Minimizing InfoNCE maximizes a lower bound on the mutual information between the two sides, a bound that can't exceed the log of the number of candidates.

Train a tiny encoder this way, then change the temperature and the batch.

DExplorable · InfoNCE: temperature, negatives, collapse

How does contrastive learning learn useful embeddings without labels, and what keeps it from collapsing?

After training with this objective, where do the embeddings end up?

How sure?
0.20

Batch size

Each item's negatives are the rest of the batch.

Objective

Without labels, a batch can't tell them apart. Off: they're masked out.

0.30
300
0.80

Multiplied by min(τ, 0.15)², so low temperatures take smaller steps.

Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

02

Predict the future: CPC

Read

Contrastive predictive codingContrastive predictive codingLearns by predicting a future representation from a context and picking the true future out of negatives with InfoNCE. encodes a sequence, summarizes the past into a context, and asks that context to pick the true future representation out of negatives drawn from other times or sequences.

In the reference's example a context scores three candidates; the true future gets probability 0.986 and the loss is 0.014. Negatives from the same sequence are harder and teach finer distinctions; easy negatives teach little.

Reference · DNN065 · Explained hereContrastive predictive coding (CPC)CPC learns representations by predicting future or withheld latent information against negative candidates. It provides a generic self-supervised framework for structured sequences and spatial contexts;
03

Two views of a row: SimCLR

Read

SimCLR makes two randomly altered views of each example, encodes both, and passes them through a small projection head. Each view's positive is its twin; every other view in the batch is a negative. The loss averages InfoNCE over all views (NT-Xent).

For tables, CodeSplash uses SCARF's alteration: replace a random share of each row's values with values drawn from the same column in other rows. In the reference's example, four unit vectors in two pairs give a loss of 0.0256: each view's twin is far more similar than the others.

04

SimCLR on penguins

Explore
Contrastive representation (SCARF)Recorded · Python and R agreeRecorded 2026-11-25 · 19 values compared
R

A SCARF contrastive encoder turned 344 rows (6 features) into 8-dimensional representations (final InfoNCE loss 3.901); neighborhoods are kept with trustworthiness 0.981. A 5-nearest-neighbor probe recovers species for 98.3% of rows (98.8% on the raw columns).

Final InfoNCE loss
3.901
Trustworthiness (k = 10)
0.9807
Alignment (lower = views closer)
1.049
Uniformity (lower = more spread)
−1.514
5-NN probe accuracy (species)
98.3%

Plots

Contrastive representation (principal components 1 and 2)Which rows group together, and how well separated are the groups?
View data
speciesComponent 1Component 2
Adelie2.774−1.047
Adelie1.9150.9130
Adelie1.7370.7030
Adelie1.223−0.5208
Adelie2.3980.7307
Adelie2.956−1.940
Adelie2.2080.9186
Adelie2.202−2.159
Adelie2.042−0.1045
Adelie2.501−1.059
Adelie1.7860.0384
Adelie2.0700.2609
Adelie2.0200.7916
Adelie3.030−2.232
Adelie2.725−2.541
Adelie2.2691.018
Adelie2.0990.6687
Adelie2.068−2.496
Adelie2.6510.9900
Adelie2.310−2.618
Adelie1.7401.707
Adelie2.039−0.2494
Adelie1.2501.983
Adelie1.506−0.2852
Adelie1.601−0.1191
Adelie1.2311.961
Adelie1.825−0.2493
Adelie1.1071.849
Adelie1.8941.726
Adelie1.734−0.3572
Adelie1.5681.551
Adelie2.251−0.3916
Adelie1.6241.375
Adelie1.983−0.6697
Adelie0.96981.364
Adelie1.553−2.436
Adelie2.011−1.594
Adelie1.7161.386
Adelie2.2671.418
Adelie1.615−1.332
Adelie2.0421.448
Adelie1.462−0.9915
Adelie2.0261.413
Adelie0.8182−1.880
Adelie1.5731.424
Adelie1.345−1.448
Adelie2.450−0.3963
Adelie2.2770.4321
Adelie1.4761.368
Adelie1.655−2.335
Adelie0.91921.819
Adelie1.112−0.8849
Adelie0.93901.951
Adelie0.5064−1.033
Adelie1.4081.915
Adelie1.230−0.4059
Adelie0.82331.800
Adelie1.120−0.5507
Adelie1.0851.582
Adelie1.310−0.5862

First 60 of 344 rows.

InfoNCE loss by epochIs the network still learning, and which part of its loss moves?
View data
PartLossEpoch
InfoNCE4.0241
InfoNCE4.0252
InfoNCE4.0363
InfoNCE3.9854
InfoNCE4.0155
InfoNCE3.9646
InfoNCE3.9797
InfoNCE3.9818
InfoNCE3.9529
InfoNCE3.95610
InfoNCE3.98311
InfoNCE3.92112
InfoNCE3.94613
InfoNCE3.94114
InfoNCE3.96215
InfoNCE3.96816
InfoNCE3.92117
InfoNCE3.93618
InfoNCE3.92319
InfoNCE3.93820
InfoNCE3.93021
InfoNCE3.92822
InfoNCE3.93623
InfoNCE3.90724
InfoNCE3.95425
InfoNCE3.87726
InfoNCE3.93527
InfoNCE3.92128
InfoNCE3.90129
InfoNCE3.91030
InfoNCE3.90831
InfoNCE3.91532
InfoNCE3.87433
InfoNCE3.88234
InfoNCE3.93035
InfoNCE3.90036
InfoNCE3.89637
InfoNCE3.90738
InfoNCE3.95239
InfoNCE3.91540
InfoNCE3.91841
InfoNCE3.88542
InfoNCE3.90243
InfoNCE3.89344
InfoNCE3.89245
InfoNCE3.90346
InfoNCE3.90447
InfoNCE3.90748
InfoNCE3.87749
InfoNCE3.90650
InfoNCE3.93751
InfoNCE3.88652
InfoNCE3.92753
InfoNCE3.86154
InfoNCE3.87555
InfoNCE3.89456
InfoNCE3.88757
InfoNCE3.89258
InfoNCE3.86159
InfoNCE3.90160

Assumptions

  • The representation uses several directions — The first principal direction holds 59% of the representation's variance.
  • Neighbors share the label at least as often as in the raw data — 5-nearest-neighbor accuracy for species: 98.3% on the representation vs 98.8% on the standardized columns.
The exact R script · R R version 4.5.1 (2025-06-13)
# Contrastive representation (SCARF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.contrastive 1.3.0 · spec 93f6670c35f62417
# Dataset: ml_penguins (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)  # cs_deep_fit_scarf: SCARF contrastive encoder (twin of codesplash.deep.generative)

# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE <- "median"
SCALE <- "standard"
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/discover.contrastive/penguins_probe/out-r")
FEATURES <- c("island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    island = "categorical",
    bill_len = "numeric",
    bill_dep = "numeric",
    flipper_len = "numeric",
    body_mass = "numeric",
    sex = "categorical"
  ),
  levels = list(
    island = c("Biscoe", "Dream", "Torgersen"),
    sex = c("female", "male")
  ),
  impute = IMPUTE,
  scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df))  # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
LABEL <- "species"
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.parquet", col_select = LABEL))[[LABEL]]
groups <- cs_deep_feature_groups(fitted)  # design columns of each feature: corruption swaps whole features
if (length(rows) < 3L) cs_error("CS_E_TOO_FEW_ROWS", what = "Contrastive representation", min = 3L, n = length(rows))  # map, trustworthiness, probe

# %% SCARF (torch for R, float64, one thread): corrupt round(c * P) features per row from other rows, InfoNCE on the projections
HIDDEN <- as.integer(unlist(c(32)))
EMB <- as.integer(8)
fit <- cs_deep_fit_scarf(
  X, groups, HIDDEN, EMB,
  activation = "relu",
  corruption = 0.6,
  temperature = 1,
  epochs = as.integer(60),
  lr = 0.001,
  batch_size = 64,
  weight_decay = 0,
  seed = 42
)
E <- fit$embedding  # encoder output (the representation), n x EMB
P2 <- cs_deep_pca2(E)  # its first two principal components, for the map

# %% How good is the representation? Neighborhoods, alignment / uniformity, and a label probe
sample <- cs_ml_sample_rows(length(rows))
k_eval <- min(10L, length(sample) - 2L)
trust <- cs_ml_trustworthiness(X[sample, , drop = FALSE], E[sample, , drop = FALSE], k_eval)
unif <- cs_deep_uniformity(fit$projection[sample, , drop = FALSE])
labels <- NULL
if (!is.null(LABEL)) labels <- as.character(df[[LABEL]][rows[sample] + 1L])
probe <- if (!is.null(labels)) cs_deep_knn_probe(E[sample, , drop = FALSE], labels) else NaN
probe_raw <- if (!is.null(labels)) cs_deep_knn_probe(X[sample, , drop = FALSE], labels) else NaN
Ec <- sweep(E, 2, colMeans(E))
ev <- if (EMB > 1L) sort(eigen(crossprod(Ec) / nrow(E), symmetric = TRUE, only.values = TRUE)$values, decreasing = TRUE) else mean(Ec[, 1]^2)
top_share <- if (sum(ev) > 0) ev[1] / sum(ev) else 1

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.contrastive/penguins_probe/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(EMB)) emb[[paste0("dim_", j)]] <- E[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
hist <- data.frame(epoch = vapply(fit$history, function(h) as.numeric(h$epoch), numeric(1)),
                   loss = vapply(fit$history, function(h) h$loss, numeric(1)))
nanoparquet::write_parquet(hist, file.path(out, "history.parquet"))

# %% Result
values <- list(
  n = length(rows), n_features = length(groups), embedding_dim = EMB, final_loss = hist$loss[nrow(hist)],
  epochs_run = fit$epochs_run, trustworthiness = trust, alignment = fit$alignment, uniformity = unif,
  top_pc_share = top_share, probe_acc = probe, probe_acc_raw = probe_raw
)
for (j in seq_len(EMB)) values[[sprintf("emb_check[%d]", j)]] <- cs_ml_checksum(E[, j], rows)
pick <- cs_ml_sample_rows(length(rows), 5000)
grp <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
  g <- df[[LABEL]][rows[pick] + 1L]
  ifelse(is.na(g), "(missing)", as.character(g))
}
charts <- list(cs_chart("map", "cluster-scatter", "Contrastive representation (principal components 1 and 2)", list(
  x = cs_col("Component 1", P2[pick, 1], "numeric"),
  y = cs_col("Component 2", P2[pick, 2], "numeric"),
  cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, grp, "categorical")
), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ","))))
charts[[2]] <- cs_chart("training", "training-components", "InfoNCE loss by epoch", list(
  x = cs_col("Epoch", hist$epoch, "numeric"),
  value = cs_col("Loss", hist$loss, "numeric"),
  component = cs_col("Part", rep("InfoNCE", nrow(hist)), "categorical")
))
collapsed <- EMB > 1L && top_share > 0.9
assumptions <- list(list(
  key = "collapse", label = "The representation uses several directions",
  status = if (collapsed) "warn" else "pass",
  detail = paste0(sprintf("The first principal direction holds %.0f%% of the representation's variance", 100 * top_share),
                  if (collapsed) " — nearly everything lies on one line (dimensional collapse)." else ".")
))
if (!is.null(LABEL) && !is.nan(probe) && !is.nan(probe_raw)) {
  assumptions[[2]] <- list(
    key = "probe", label = "Neighbors share the label at least as often as in the raw data",
    status = if (probe < probe_raw - 0.05) "warn" else "pass",
    detail = sprintf("5-nearest-neighbor accuracy for %s: %.1f%% on the representation vs %.1f%% on the standardized columns.", LABEL, 100 * probe, 100 * probe_raw)
  )
}
summary <- sprintf("A SCARF contrastive encoder turned %d rows (%d features) into %d-dimensional representations (final InfoNCE loss %.3f); neighborhoods are kept with trustworthiness %.3f.",
                   length(rows), length(groups), EMB, values$final_loss, trust)
if (!is.null(LABEL) && !is.nan(probe)) summary <- paste0(summary, sprintf(" A 5-nearest-neighbor probe recovers %s for %.1f%% of rows (%.1f%% on the raw columns).", LABEL, 100 * probe, 100 * probe_raw))
statistics <- list(
  list(key = "final_loss", label = "Final InfoNCE loss", value = values$final_loss),
  list(key = "trustworthiness", label = sprintf("Trustworthiness (k = %d)", k_eval), value = trust),
  list(key = "alignment", label = "Alignment (lower = views closer)", value = values$alignment),
  list(key = "uniformity", label = "Uniformity (lower = more spread)", value = unif)
)
if (!is.null(LABEL)) statistics[[5]] <- list(key = "probe_acc", label = sprintf("5-NN probe accuracy (%s)", LABEL), value = probe, format = "percent")
cs_publish(list(
  title = "Contrastive representation (SCARF)",
  engine = cs_engine_info("torch", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = statistics,
  charts = charts,
  assumptions = assumptions,
  values = values,
  warnings = warnings,
  artifacts = list(
    list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"),
    list(key = "history", path = file.path(out, "history.parquet"), format = "parquet")
  )
))
Python

A SCARF contrastive encoder turned 344 rows (6 features) into 8-dimensional representations (final InfoNCE loss 3.901); neighborhoods are kept with trustworthiness 0.981. A 5-nearest-neighbor probe recovers species for 98.3% of rows (98.8% on the raw columns).

Final InfoNCE loss
3.901
Trustworthiness (k = 10)
0.9807
Alignment (lower = views closer)
1.049
Uniformity (lower = more spread)
−1.514
5-NN probe accuracy (species)
98.3%

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • The representation uses several directions — The first principal direction holds 59% of the representation's variance.
  • Neighbors share the label at least as often as in the raw data — 5-nearest-neighbor accuracy for species: 98.3% on the representation vs 98.8% on the standardized columns.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Contrastive representation (SCARF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.contrastive 1.3.0 · spec 93f6670c35f62417
# Dataset: ml_penguins (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.deep import generative as gen  # twin of codesplashr::cs_deep_fit_scarf (shared weights and corruption draws)
from codesplash.ml import embed as csembed

# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE = "median"
SCALE = "standard"
from codesplash.deep import trainer as deep_trainer  # training options, live progress, checkpoints (twin: cs_deep_trainer_*)

deep_trainer.configure(
    {
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/discover.contrastive/penguins_probe/out-python",
)
FEATURES = ["island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"]
df = pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "island": "categorical",
        "bill_len": "numeric",
        "bill_dep": "numeric",
        "flipper_len": "numeric",
        "body_mass": "numeric",
        "sex": "categorical",
    },
    levels={
        "island": ["Biscoe", "Dream", "Torgersen"],
        "sex": ["female", "male"],
    },
    impute=IMPUTE,
    scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df)  # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
LABEL = "species"
if LABEL:
    df[LABEL] = pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=[LABEL])[LABEL]
groups = gen.feature_groups(fitted)  # design columns of each feature: corruption swaps whole features
if len(rows) < 3:  # the map, trustworthiness (k = n − 2) and the probe need three rows
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="Contrastive representation", min=3, n=len(rows))

# %% SCARF (PyTorch, float64, one thread): corrupt round(c·P) features per row from other rows, InfoNCE on the projections
HIDDEN = [int(u) for u in [32]]
EMB = 8
fit = gen.fit_scarf(
    X, groups, HIDDEN, EMB,
    activation="relu",
    corruption=0.6,
    temperature=1,
    epochs=60,
    lr=0.001,
    batch_size=64,
    weight_decay=0,
    seed=42,
)
E = fit["embedding"]  # encoder output (the representation), n × EMB
P2 = gen.pca2(E)  # its first two principal components, for the map

# %% How good is the representation? Neighborhoods, alignment / uniformity, and a label probe
sample = csembed.sample_rows(len(rows))
k_eval = min(10, len(sample) - 2)
trust = csembed.trustworthiness(X[sample], E[sample], k_eval)
unif = gen.uniformity(fit["projection"][sample])
labels = None
if LABEL:
    labels = [None if pd.isna(v) else str(v) for v in df[LABEL].iloc[rows[sample]]]
probe = gen.knn_probe(E[sample], labels) if labels else float("nan")
probe_raw = gen.knn_probe(X[sample], labels) if labels else float("nan")
Ec = E - E.mean(axis=0)
ev = np.sort(np.linalg.eigvalsh(Ec.T @ Ec / len(E)))[::-1] if EMB > 1 else np.array([float(np.mean(Ec[:, 0] ** 2))])
top_share = float(ev[0] / ev.sum()) if ev.sum() > 0 else 1.0

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.contrastive/penguins_probe/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64), **{f"dim_{j + 1}": E[:, j] for j in range(EMB)}})
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
history = pd.DataFrame({"epoch": [h["epoch"] for h in fit["history"]], "loss": [h["loss"] for h in fit["history"]]})
history.to_parquet(os.path.join(out, "history.parquet"), index=False)

# %% Result
values = {
    "n": len(rows),
    "n_features": len(groups),
    "embedding_dim": EMB,
    "final_loss": float(fit["history"][-1]["loss"]),
    "epochs_run": int(fit["epochs_run"]),
    "trustworthiness": trust,
    "alignment": float(fit["alignment"]),
    "uniformity": unif,
    "top_pc_share": top_share,
    "probe_acc": probe,
    "probe_acc_raw": probe_raw,
}
for j in range(EMB):
    values[f"emb_check[{j + 1}]"] = csembed.checksum(E[:, j], rows)
pick = csembed.sample_rows(len(rows), 5000)
grp = [("All rows" if LABEL is None else ("(missing)" if pd.isna(v) else str(v))) for v in (df[LABEL].iloc[rows[pick]] if LABEL else [None] * len(pick))]
charts = [cs.chart("map", "cluster-scatter", "Contrastive representation (principal components 1 and 2)", {
    "x": cs.col("Component 1", P2[pick, 0], "numeric"),
    "y": cs.col("Component 2", P2[pick, 1], "numeric"),
    "cluster": cs.col(LABEL or "Group", grp, "categorical"),
}, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown.")]
ep = [h["epoch"] for h in fit["history"]]
charts.append(cs.chart("training", "training-components", "InfoNCE loss by epoch", {
    "x": cs.col("Epoch", ep, "numeric"),
    "value": cs.col("Loss", [h["loss"] for h in fit["history"]], "numeric"),
    "component": cs.col("Part", ["InfoNCE"] * len(ep), "categorical"),
}))
assumptions = [{
    "key": "collapse",
    "label": "The representation uses several directions",
    "status": "warn" if (EMB > 1 and top_share > 0.9) else "pass",
    "detail": f"The first principal direction holds {top_share:.0%} of the representation's variance"
              + (" — nearly everything lies on one line (dimensional collapse)." if EMB > 1 and top_share > 0.9 else "."),
}]
if LABEL and probe == probe and probe_raw == probe_raw:
    assumptions.append({
        "key": "probe",
        "label": "Neighbors share the label at least as often as in the raw data",
        "status": "warn" if probe < probe_raw - 0.05 else "pass",
        "detail": f"5-nearest-neighbor accuracy for {LABEL}: {probe:.1%} on the representation vs {probe_raw:.1%} on the standardized columns.",
    })
summary = (
    f"A SCARF contrastive encoder turned {len(rows)} rows ({len(groups)} features) into {EMB}-dimensional representations "
    f"(final InfoNCE loss {values['final_loss']:.3f}); neighborhoods are kept with trustworthiness {trust:.3f}."
)
if LABEL and probe == probe:
    summary += f" A 5-nearest-neighbor probe recovers {LABEL} for {probe:.1%} of rows ({probe_raw:.1%} on the raw columns)."
cs.publish({
    "title": "Contrastive representation (SCARF)",
    "engine": cs.engine_info("torch", "numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "final_loss", "label": "Final InfoNCE loss", "value": values["final_loss"]},
        {"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": trust},
        {"key": "alignment", "label": "Alignment (lower = views closer)", "value": values["alignment"]},
        {"key": "uniformity", "label": "Uniformity (lower = more spread)", "value": unif},
    ] +([{"key": "probe_acc", "label": f"5-NN probe accuracy ({LABEL})", "value": probe, "format": "percent"}] if LABEL else []),
    "charts": charts,
    "assumptions": assumptions,
    "values": values,
    "warnings": warnings,
    "artifacts": [
        {"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"},
        {"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet"},
    ],
})

The encoder turned 6 columns into 8 numbers per row. A nearest-neighbor probeNearest-neighbor probeHow often a row's nearest neighbors in a representation share its label — a check that the representation kept the label. guesses each penguin's species from its nearest neighbor in the representation: 98.3%, against 98.8% on the standardized columns themselves.

The representation didn't beat the raw columns here. On a small table with informative columns, that's common. Report the raw baseline every time.

05

Alignment, uniformity and collapse

Read

Two numbers describe a contrastive representation (alignment and uniformityAlignment and uniformityTwo checks on normalized representations — views of a row should sit close (alignment) while rows spread out (uniformity).): alignment, how close positive pairs end up, here 1.05; and uniformity, how evenly rows spread over the sphere, here −1.51 (more negative is more even).

The first principal component holds 59.3% of the representation's variance. A share near 100% would be dimensional collapseDimensional collapseA learned representation that uses only one or a few directions, so most of its coordinates repeat the same information.: everything squeezed onto a line.

06

Without a label to check

Explore
Contrastive representation (SCARF)Recorded · Python and R agreeRecorded 2026-11-25 · 17 values compared · largest relative difference 9.4e-6
R

A SCARF contrastive encoder turned 532 rows (7 features) into 6-dimensional representations (final InfoNCE loss 4.637); neighborhoods are kept with trustworthiness 0.889.

Final InfoNCE loss
4.637
Trustworthiness (k = 10)
0.8894
Alignment (lower = views closer)
1.022
Uniformity (lower = more spread)
−1.505

Plots

Contrastive representation (principal components 1 and 2)Which rows group together, and how well separated are the groups?
View data
GroupComponent 1Component 2
All rows0.15290.1176
All rows0.5808−0.7656
All rows−1.493−0.3858
All rows−1.376−1.539
All rows1.6950.5202
All rows−2.9402.207
All rows0.59620.7607
All rows0.2770−0.1655
All rows−3.2592.627
All rows−0.0391−0.9714
All rows2.1151.712
All rows−0.90360.0667
All rows0.2098−1.397
All rows−3.2472.539
All rows1.047−1.206
All rows−0.21430.3281
All rows2.5371.007
All rows−3.3810.3406
All rows0.4327−0.4974
All rows0.88490.1688
All rows1.0050.3534
All rows0.41790.7618
All rows−0.90690.8071
All rows2.2800.4347
All rows1.304−0.4955
All rows−0.7591−0.6247
All rows2.1231.263
All rows0.08010.1481
All rows−0.9445−0.5757
All rows1.407−0.1356
All rows1.319−0.1765
All rows−0.09440.2107
All rows0.0058−0.1361
All rows−0.03770.0162
All rows0.8972−0.9834
All rows−2.7311.267
All rows3.6180.0704
All rows2.6721.723
All rows2.461−1.061
All rows0.23090.1788
All rows−2.552−0.5955
All rows3.2370.5763
All rows−0.42950.7687
All rows2.4900.2859
All rows2.023−0.6431
All rows−0.21380.5316
All rows−0.5985−0.4201
All rows5.116−0.4794
All rows−0.1509−0.4802
All rows−0.8922−1.485
All rows−0.24400.1274
All rows2.0151.008
All rows−1.072−0.2194
All rows−0.1321−0.4667
All rows0.6377−0.2038
All rows−0.8683−0.4693
All rows0.9331−0.0149
All rows0.99111.709
All rows−0.20351.373
All rows−2.617−0.5470

First 60 of 532 rows.

InfoNCE loss by epochIs the network still learning, and which part of its loss moves?
View data
PartLossEpoch
InfoNCE4.7401
InfoNCE4.7292
InfoNCE4.7493
InfoNCE4.7694
InfoNCE4.7375
InfoNCE4.7266
InfoNCE4.7257
InfoNCE4.7348
InfoNCE4.7239
InfoNCE4.72010
InfoNCE4.68511
InfoNCE4.73012
InfoNCE4.70513
InfoNCE4.70314
InfoNCE4.71515
InfoNCE4.67516
InfoNCE4.67917
InfoNCE4.67718
InfoNCE4.66419
InfoNCE4.66720
InfoNCE4.70821
InfoNCE4.69022
InfoNCE4.67923
InfoNCE4.64024
InfoNCE4.65125
InfoNCE4.65726
InfoNCE4.65527
InfoNCE4.64228
InfoNCE4.66829
InfoNCE4.63730

Assumptions

  • The representation uses several directions — The first principal direction holds 51% of the representation's variance.
The exact R script · R R version 4.5.1 (2025-06-13)
# Contrastive representation (SCARF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.contrastive 1.3.0 · spec 9934367f1c30e3c5
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)  # cs_deep_fit_scarf: SCARF contrastive encoder (twin of codesplash.deep.generative)

# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE <- "median"
SCALE <- "standard"
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/discover.contrastive/pima_no_label/out-r")
FEATURES <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    npreg = "numeric",
    glu = "numeric",
    bp = "numeric",
    skin = "numeric",
    bmi = "numeric",
    ped = "numeric",
    age = "numeric"
  ),
  levels = list(
  ),
  impute = IMPUTE,
  scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df))  # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
LABEL <- NULL
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = LABEL))[[LABEL]]
groups <- cs_deep_feature_groups(fitted)  # design columns of each feature: corruption swaps whole features
if (length(rows) < 3L) cs_error("CS_E_TOO_FEW_ROWS", what = "Contrastive representation", min = 3L, n = length(rows))  # map, trustworthiness, probe

# %% SCARF (torch for R, float64, one thread): corrupt round(c * P) features per row from other rows, InfoNCE on the projections
HIDDEN <- as.integer(unlist(c(24, 16)))
EMB <- as.integer(6)
fit <- cs_deep_fit_scarf(
  X, groups, HIDDEN, EMB,
  activation = "relu",
  corruption = 0.6,
  temperature = 1,
  epochs = as.integer(30),
  lr = 0.001,
  batch_size = 128,
  weight_decay = 0.0001,
  seed = 42
)
E <- fit$embedding  # encoder output (the representation), n x EMB
P2 <- cs_deep_pca2(E)  # its first two principal components, for the map

# %% How good is the representation? Neighborhoods, alignment / uniformity, and a label probe
sample <- cs_ml_sample_rows(length(rows))
k_eval <- min(10L, length(sample) - 2L)
trust <- cs_ml_trustworthiness(X[sample, , drop = FALSE], E[sample, , drop = FALSE], k_eval)
unif <- cs_deep_uniformity(fit$projection[sample, , drop = FALSE])
labels <- NULL
if (!is.null(LABEL)) labels <- as.character(df[[LABEL]][rows[sample] + 1L])
probe <- if (!is.null(labels)) cs_deep_knn_probe(E[sample, , drop = FALSE], labels) else NaN
probe_raw <- if (!is.null(labels)) cs_deep_knn_probe(X[sample, , drop = FALSE], labels) else NaN
Ec <- sweep(E, 2, colMeans(E))
ev <- if (EMB > 1L) sort(eigen(crossprod(Ec) / nrow(E), symmetric = TRUE, only.values = TRUE)$values, decreasing = TRUE) else mean(Ec[, 1]^2)
top_share <- if (sum(ev) > 0) ev[1] / sum(ev) else 1

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.contrastive/pima_no_label/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(EMB)) emb[[paste0("dim_", j)]] <- E[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
hist <- data.frame(epoch = vapply(fit$history, function(h) as.numeric(h$epoch), numeric(1)),
                   loss = vapply(fit$history, function(h) h$loss, numeric(1)))
nanoparquet::write_parquet(hist, file.path(out, "history.parquet"))

# %% Result
values <- list(
  n = length(rows), n_features = length(groups), embedding_dim = EMB, final_loss = hist$loss[nrow(hist)],
  epochs_run = fit$epochs_run, trustworthiness = trust, alignment = fit$alignment, uniformity = unif,
  top_pc_share = top_share, probe_acc = probe, probe_acc_raw = probe_raw
)
for (j in seq_len(EMB)) values[[sprintf("emb_check[%d]", j)]] <- cs_ml_checksum(E[, j], rows)
pick <- cs_ml_sample_rows(length(rows), 5000)
grp <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
  g <- df[[LABEL]][rows[pick] + 1L]
  ifelse(is.na(g), "(missing)", as.character(g))
}
charts <- list(cs_chart("map", "cluster-scatter", "Contrastive representation (principal components 1 and 2)", list(
  x = cs_col("Component 1", P2[pick, 1], "numeric"),
  y = cs_col("Component 2", P2[pick, 2], "numeric"),
  cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, grp, "categorical")
), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ","))))
charts[[2]] <- cs_chart("training", "training-components", "InfoNCE loss by epoch", list(
  x = cs_col("Epoch", hist$epoch, "numeric"),
  value = cs_col("Loss", hist$loss, "numeric"),
  component = cs_col("Part", rep("InfoNCE", nrow(hist)), "categorical")
))
collapsed <- EMB > 1L && top_share > 0.9
assumptions <- list(list(
  key = "collapse", label = "The representation uses several directions",
  status = if (collapsed) "warn" else "pass",
  detail = paste0(sprintf("The first principal direction holds %.0f%% of the representation's variance", 100 * top_share),
                  if (collapsed) " — nearly everything lies on one line (dimensional collapse)." else ".")
))
if (!is.null(LABEL) && !is.nan(probe) && !is.nan(probe_raw)) {
  assumptions[[2]] <- list(
    key = "probe", label = "Neighbors share the label at least as often as in the raw data",
    status = if (probe < probe_raw - 0.05) "warn" else "pass",
    detail = sprintf("5-nearest-neighbor accuracy for %s: %.1f%% on the representation vs %.1f%% on the standardized columns.", LABEL, 100 * probe, 100 * probe_raw)
  )
}
summary <- sprintf("A SCARF contrastive encoder turned %d rows (%d features) into %d-dimensional representations (final InfoNCE loss %.3f); neighborhoods are kept with trustworthiness %.3f.",
                   length(rows), length(groups), EMB, values$final_loss, trust)
if (!is.null(LABEL) && !is.nan(probe)) summary <- paste0(summary, sprintf(" A 5-nearest-neighbor probe recovers %s for %.1f%% of rows (%.1f%% on the raw columns).", LABEL, 100 * probe, 100 * probe_raw))
statistics <- list(
  list(key = "final_loss", label = "Final InfoNCE loss", value = values$final_loss),
  list(key = "trustworthiness", label = sprintf("Trustworthiness (k = %d)", k_eval), value = trust),
  list(key = "alignment", label = "Alignment (lower = views closer)", value = values$alignment),
  list(key = "uniformity", label = "Uniformity (lower = more spread)", value = unif)
)
if (!is.null(LABEL)) statistics[[5]] <- list(key = "probe_acc", label = sprintf("5-NN probe accuracy (%s)", LABEL), value = probe, format = "percent")
cs_publish(list(
  title = "Contrastive representation (SCARF)",
  engine = cs_engine_info("torch", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = statistics,
  charts = charts,
  assumptions = assumptions,
  values = values,
  warnings = warnings,
  artifacts = list(
    list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"),
    list(key = "history", path = file.path(out, "history.parquet"), format = "parquet")
  )
))
Python

A SCARF contrastive encoder turned 532 rows (7 features) into 6-dimensional representations (final InfoNCE loss 4.637); neighborhoods are kept with trustworthiness 0.889.

Final InfoNCE loss
4.637
Trustworthiness (k = 10)
0.8894
Alignment (lower = views closer)
1.022
Uniformity (lower = more spread)
−1.505

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • The representation uses several directions — The first principal direction holds 51% of the representation's variance.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Contrastive representation (SCARF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.contrastive 1.3.0 · spec 9934367f1c30e3c5
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.deep import generative as gen  # twin of codesplashr::cs_deep_fit_scarf (shared weights and corruption draws)
from codesplash.ml import embed as csembed

# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE = "median"
SCALE = "standard"
from codesplash.deep import trainer as deep_trainer  # training options, live progress, checkpoints (twin: cs_deep_trainer_*)

deep_trainer.configure(
    {
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/discover.contrastive/pima_no_label/out-python",
)
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "npreg": "numeric",
        "glu": "numeric",
        "bp": "numeric",
        "skin": "numeric",
        "bmi": "numeric",
        "ped": "numeric",
        "age": "numeric",
    },
    levels={
    },
    impute=IMPUTE,
    scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df)  # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
LABEL = None
if LABEL:
    df[LABEL] = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=[LABEL])[LABEL]
groups = gen.feature_groups(fitted)  # design columns of each feature: corruption swaps whole features
if len(rows) < 3:  # the map, trustworthiness (k = n − 2) and the probe need three rows
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="Contrastive representation", min=3, n=len(rows))

# %% SCARF (PyTorch, float64, one thread): corrupt round(c·P) features per row from other rows, InfoNCE on the projections
HIDDEN = [int(u) for u in [24, 16]]
EMB = 6
fit = gen.fit_scarf(
    X, groups, HIDDEN, EMB,
    activation="relu",
    corruption=0.6,
    temperature=1,
    epochs=30,
    lr=0.001,
    batch_size=128,
    weight_decay=0.0001,
    seed=42,
)
E = fit["embedding"]  # encoder output (the representation), n × EMB
P2 = gen.pca2(E)  # its first two principal components, for the map

# %% How good is the representation? Neighborhoods, alignment / uniformity, and a label probe
sample = csembed.sample_rows(len(rows))
k_eval = min(10, len(sample) - 2)
trust = csembed.trustworthiness(X[sample], E[sample], k_eval)
unif = gen.uniformity(fit["projection"][sample])
labels = None
if LABEL:
    labels = [None if pd.isna(v) else str(v) for v in df[LABEL].iloc[rows[sample]]]
probe = gen.knn_probe(E[sample], labels) if labels else float("nan")
probe_raw = gen.knn_probe(X[sample], labels) if labels else float("nan")
Ec = E - E.mean(axis=0)
ev = np.sort(np.linalg.eigvalsh(Ec.T @ Ec / len(E)))[::-1] if EMB > 1 else np.array([float(np.mean(Ec[:, 0] ** 2))])
top_share = float(ev[0] / ev.sum()) if ev.sum() > 0 else 1.0

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.contrastive/pima_no_label/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64), **{f"dim_{j + 1}": E[:, j] for j in range(EMB)}})
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
history = pd.DataFrame({"epoch": [h["epoch"] for h in fit["history"]], "loss": [h["loss"] for h in fit["history"]]})
history.to_parquet(os.path.join(out, "history.parquet"), index=False)

# %% Result
values = {
    "n": len(rows),
    "n_features": len(groups),
    "embedding_dim": EMB,
    "final_loss": float(fit["history"][-1]["loss"]),
    "epochs_run": int(fit["epochs_run"]),
    "trustworthiness": trust,
    "alignment": float(fit["alignment"]),
    "uniformity": unif,
    "top_pc_share": top_share,
    "probe_acc": probe,
    "probe_acc_raw": probe_raw,
}
for j in range(EMB):
    values[f"emb_check[{j + 1}]"] = csembed.checksum(E[:, j], rows)
pick = csembed.sample_rows(len(rows), 5000)
grp = [("All rows" if LABEL is None else ("(missing)" if pd.isna(v) else str(v))) for v in (df[LABEL].iloc[rows[pick]] if LABEL else [None] * len(pick))]
charts = [cs.chart("map", "cluster-scatter", "Contrastive representation (principal components 1 and 2)", {
    "x": cs.col("Component 1", P2[pick, 0], "numeric"),
    "y": cs.col("Component 2", P2[pick, 1], "numeric"),
    "cluster": cs.col(LABEL or "Group", grp, "categorical"),
}, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown.")]
ep = [h["epoch"] for h in fit["history"]]
charts.append(cs.chart("training", "training-components", "InfoNCE loss by epoch", {
    "x": cs.col("Epoch", ep, "numeric"),
    "value": cs.col("Loss", [h["loss"] for h in fit["history"]], "numeric"),
    "component": cs.col("Part", ["InfoNCE"] * len(ep), "categorical"),
}))
assumptions = [{
    "key": "collapse",
    "label": "The representation uses several directions",
    "status": "warn" if (EMB > 1 and top_share > 0.9) else "pass",
    "detail": f"The first principal direction holds {top_share:.0%} of the representation's variance"
              + (" — nearly everything lies on one line (dimensional collapse)." if EMB > 1 and top_share > 0.9 else "."),
}]
if LABEL and probe == probe and probe_raw == probe_raw:
    assumptions.append({
        "key": "probe",
        "label": "Neighbors share the label at least as often as in the raw data",
        "status": "warn" if probe < probe_raw - 0.05 else "pass",
        "detail": f"5-nearest-neighbor accuracy for {LABEL}: {probe:.1%} on the representation vs {probe_raw:.1%} on the standardized columns.",
    })
summary = (
    f"A SCARF contrastive encoder turned {len(rows)} rows ({len(groups)} features) into {EMB}-dimensional representations "
    f"(final InfoNCE loss {values['final_loss']:.3f}); neighborhoods are kept with trustworthiness {trust:.3f}."
)
if LABEL and probe == probe:
    summary += f" A 5-nearest-neighbor probe recovers {LABEL} for {probe:.1%} of rows ({probe_raw:.1%} on the raw columns)."
cs.publish({
    "title": "Contrastive representation (SCARF)",
    "engine": cs.engine_info("torch", "numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "final_loss", "label": "Final InfoNCE loss", "value": values["final_loss"]},
        {"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": trust},
        {"key": "alignment", "label": "Alignment (lower = views closer)", "value": values["alignment"]},
        {"key": "uniformity", "label": "Uniformity (lower = more spread)", "value": unif},
    ] +([{"key": "probe_acc", "label": f"5-NN probe accuracy ({LABEL})", "value": probe, "format": "percent"}] if LABEL else []),
    "charts": charts,
    "assumptions": assumptions,
    "values": values,
    "warnings": warnings,
    "artifacts": [
        {"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"},
        {"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet"},
    ],
})

With no label column there is no probe. Here the map's trustworthiness, 0.889, and the top component's share, 51.0%, are what you have. Before trusting the representation for a task, find a few labeled rows and probe.

07

Negatives that aren't negative

Predict

Predict first

In a batch of 256 customer rows, SimCLR treats every other row as a negative for each anchor. Are they all truly different?

They're all true negativesSome are the same kind of row, and get pushed apart anyway
Reveal

No. Rows of the same kind, say two near-identical customers, are still pushed apart. With few distinct kinds, false negatives can hurt; larger temperatures soften the push.

08

Many negatives, cheaply: MoCo

Read

InfoNCE likes many negatives, but SimCLR's come from the batch, so more negatives means bigger batches. MoCo keeps a queue of keys from recent batches instead. The keys come from a momentum encoderMomentum encoderA copy of the encoder whose weights trail the trained one as a slow moving average; it gives stable targets or keys., a copy whose weights trail the trained encoder as a slow moving average, so old and new keys stay comparable.

In the reference's example one momentum update moves the key weights to (0.602, 0.299), and the query's InfoNCE loss against three keys is 0.0041.

Reference · DNN067 · Explained hereMomentum 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.
09

What runs here

Read
10

Check: contrastive learning

Checkpoint

Check yourself

What does contrastive predictive coding ask its context representation to do?

Show the answer

Answer: a

CPC is InfoNCE with the future as the positive. It never reconstructs raw inputs.

Check yourself

InfoNCE with N candidates bounds the mutual information between the two sides. What limits that bound?

Show the answer

Answer: b

The bound can't exceed log N, one reason contrastive methods want many negatives.

Check yourself

In SimCLR, what is a view's positive?

Show the answer

Answer: a

Positives come from the alterations, not from labels. Every other view in the batch serves as a negative.

Check yourself

A contrastive representation's probe accuracy is slightly below the probe on raw standardized columns. What should you report?

Show the answer

Answer: b

The raw-column probe is the baseline. A representation has to earn its place against it, and on small, informative tables it often doesn't.

Check yourself

What does lowering InfoNCE's temperature do?

Show the answer

Answer: a

Dividing similarities by a smaller τ stretches their differences, so the closest negatives dominate the loss.

Check yourself

Why does MoCo encode its keys with a slowly updated momentum encoder?

Show the answer

Answer: b

If the key encoder changed as fast as the query encoder, keys in the queue would come from many different encoders and the comparison would be inconsistent.

Check yourself

What does MoCo's queue buy compared with SimCLR's batch negatives?

Show the answer

Answer: a

Keys from recent batches are reused as negatives, so the number of negatives no longer depends on batch size. False negatives remain possible.

11

Recap

Recap
  • InfoNCE classifies the positive among candidates; temperature sets how hard near misses are punished.
  • CPC predicts the future, SimCLR matches two views against the batch, MoCo uses a momentum encoder and a queue.
  • Check a representation with a probe against raw columns, alignment and uniformity, and the top component's share.
  • SimCLR runs in Discover as Contrastive representation; CPC and MoCo are explained here.

Concepts in this lesson