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.
What runs in CodeSplash
- DNN065Contrastive predictive coding (CPC) Explained here
- DNN066SimCLR Runs in CodeSplash (Experimental)
- DNN067Momentum contrast (MoCo) Explained here
- Contrastive representation (SCARF) Experimental
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
Find your partner
ReadContrastive 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 , one positive 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.:
The temperature 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?
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.
Multiplied by min(τ, 0.15)², so low temperatures take smaller steps.
Commit your prediction above to see the result
Make your prediction to see the result.
Predict the future: CPC
ReadContrastive 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;Two views of a row: SimCLR
ReadSimCLR 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.
SimCLR on penguins
ExploreA 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
View data
| species | Component 1 | Component 2 |
|---|---|---|
| Adelie | 2.774 | −1.047 |
| Adelie | 1.915 | 0.9130 |
| Adelie | 1.737 | 0.7030 |
| Adelie | 1.223 | −0.5208 |
| Adelie | 2.398 | 0.7307 |
| Adelie | 2.956 | −1.940 |
| Adelie | 2.208 | 0.9186 |
| Adelie | 2.202 | −2.159 |
| Adelie | 2.042 | −0.1045 |
| Adelie | 2.501 | −1.059 |
| Adelie | 1.786 | 0.0384 |
| Adelie | 2.070 | 0.2609 |
| Adelie | 2.020 | 0.7916 |
| Adelie | 3.030 | −2.232 |
| Adelie | 2.725 | −2.541 |
| Adelie | 2.269 | 1.018 |
| Adelie | 2.099 | 0.6687 |
| Adelie | 2.068 | −2.496 |
| Adelie | 2.651 | 0.9900 |
| Adelie | 2.310 | −2.618 |
| Adelie | 1.740 | 1.707 |
| Adelie | 2.039 | −0.2494 |
| Adelie | 1.250 | 1.983 |
| Adelie | 1.506 | −0.2852 |
| Adelie | 1.601 | −0.1191 |
| Adelie | 1.231 | 1.961 |
| Adelie | 1.825 | −0.2493 |
| Adelie | 1.107 | 1.849 |
| Adelie | 1.894 | 1.726 |
| Adelie | 1.734 | −0.3572 |
| Adelie | 1.568 | 1.551 |
| Adelie | 2.251 | −0.3916 |
| Adelie | 1.624 | 1.375 |
| Adelie | 1.983 | −0.6697 |
| Adelie | 0.9698 | 1.364 |
| Adelie | 1.553 | −2.436 |
| Adelie | 2.011 | −1.594 |
| Adelie | 1.716 | 1.386 |
| Adelie | 2.267 | 1.418 |
| Adelie | 1.615 | −1.332 |
| Adelie | 2.042 | 1.448 |
| Adelie | 1.462 | −0.9915 |
| Adelie | 2.026 | 1.413 |
| Adelie | 0.8182 | −1.880 |
| Adelie | 1.573 | 1.424 |
| Adelie | 1.345 | −1.448 |
| Adelie | 2.450 | −0.3963 |
| Adelie | 2.277 | 0.4321 |
| Adelie | 1.476 | 1.368 |
| Adelie | 1.655 | −2.335 |
| Adelie | 0.9192 | 1.819 |
| Adelie | 1.112 | −0.8849 |
| Adelie | 0.9390 | 1.951 |
| Adelie | 0.5064 | −1.033 |
| Adelie | 1.408 | 1.915 |
| Adelie | 1.230 | −0.4059 |
| Adelie | 0.8233 | 1.800 |
| Adelie | 1.120 | −0.5507 |
| Adelie | 1.085 | 1.582 |
| Adelie | 1.310 | −0.5862 |
First 60 of 344 rows.
View data
| Part | Loss | Epoch |
|---|---|---|
| InfoNCE | 4.024 | 1 |
| InfoNCE | 4.025 | 2 |
| InfoNCE | 4.036 | 3 |
| InfoNCE | 3.985 | 4 |
| InfoNCE | 4.015 | 5 |
| InfoNCE | 3.964 | 6 |
| InfoNCE | 3.979 | 7 |
| InfoNCE | 3.981 | 8 |
| InfoNCE | 3.952 | 9 |
| InfoNCE | 3.956 | 10 |
| InfoNCE | 3.983 | 11 |
| InfoNCE | 3.921 | 12 |
| InfoNCE | 3.946 | 13 |
| InfoNCE | 3.941 | 14 |
| InfoNCE | 3.962 | 15 |
| InfoNCE | 3.968 | 16 |
| InfoNCE | 3.921 | 17 |
| InfoNCE | 3.936 | 18 |
| InfoNCE | 3.923 | 19 |
| InfoNCE | 3.938 | 20 |
| InfoNCE | 3.930 | 21 |
| InfoNCE | 3.928 | 22 |
| InfoNCE | 3.936 | 23 |
| InfoNCE | 3.907 | 24 |
| InfoNCE | 3.954 | 25 |
| InfoNCE | 3.877 | 26 |
| InfoNCE | 3.935 | 27 |
| InfoNCE | 3.921 | 28 |
| InfoNCE | 3.901 | 29 |
| InfoNCE | 3.910 | 30 |
| InfoNCE | 3.908 | 31 |
| InfoNCE | 3.915 | 32 |
| InfoNCE | 3.874 | 33 |
| InfoNCE | 3.882 | 34 |
| InfoNCE | 3.930 | 35 |
| InfoNCE | 3.900 | 36 |
| InfoNCE | 3.896 | 37 |
| InfoNCE | 3.907 | 38 |
| InfoNCE | 3.952 | 39 |
| InfoNCE | 3.915 | 40 |
| InfoNCE | 3.918 | 41 |
| InfoNCE | 3.885 | 42 |
| InfoNCE | 3.902 | 43 |
| InfoNCE | 3.893 | 44 |
| InfoNCE | 3.892 | 45 |
| InfoNCE | 3.903 | 46 |
| InfoNCE | 3.904 | 47 |
| InfoNCE | 3.907 | 48 |
| InfoNCE | 3.877 | 49 |
| InfoNCE | 3.906 | 50 |
| InfoNCE | 3.937 | 51 |
| InfoNCE | 3.886 | 52 |
| InfoNCE | 3.927 | 53 |
| InfoNCE | 3.861 | 54 |
| InfoNCE | 3.875 | 55 |
| InfoNCE | 3.894 | 56 |
| InfoNCE | 3.887 | 57 |
| InfoNCE | 3.892 | 58 |
| InfoNCE | 3.861 | 59 |
| InfoNCE | 3.901 | 60 |
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")
)
))
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.
Alignment, uniformity and collapse
ReadTwo 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.
Without a label to check
ExploreA 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
View data
| Group | Component 1 | Component 2 |
|---|---|---|
| All rows | 0.1529 | 0.1176 |
| All rows | 0.5808 | −0.7656 |
| All rows | −1.493 | −0.3858 |
| All rows | −1.376 | −1.539 |
| All rows | 1.695 | 0.5202 |
| All rows | −2.940 | 2.207 |
| All rows | 0.5962 | 0.7607 |
| All rows | 0.2770 | −0.1655 |
| All rows | −3.259 | 2.627 |
| All rows | −0.0391 | −0.9714 |
| All rows | 2.115 | 1.712 |
| All rows | −0.9036 | 0.0667 |
| All rows | 0.2098 | −1.397 |
| All rows | −3.247 | 2.539 |
| All rows | 1.047 | −1.206 |
| All rows | −0.2143 | 0.3281 |
| All rows | 2.537 | 1.007 |
| All rows | −3.381 | 0.3406 |
| All rows | 0.4327 | −0.4974 |
| All rows | 0.8849 | 0.1688 |
| All rows | 1.005 | 0.3534 |
| All rows | 0.4179 | 0.7618 |
| All rows | −0.9069 | 0.8071 |
| All rows | 2.280 | 0.4347 |
| All rows | 1.304 | −0.4955 |
| All rows | −0.7591 | −0.6247 |
| All rows | 2.123 | 1.263 |
| All rows | 0.0801 | 0.1481 |
| All rows | −0.9445 | −0.5757 |
| All rows | 1.407 | −0.1356 |
| All rows | 1.319 | −0.1765 |
| All rows | −0.0944 | 0.2107 |
| All rows | 0.0058 | −0.1361 |
| All rows | −0.0377 | 0.0162 |
| All rows | 0.8972 | −0.9834 |
| All rows | −2.731 | 1.267 |
| All rows | 3.618 | 0.0704 |
| All rows | 2.672 | 1.723 |
| All rows | 2.461 | −1.061 |
| All rows | 0.2309 | 0.1788 |
| All rows | −2.552 | −0.5955 |
| All rows | 3.237 | 0.5763 |
| All rows | −0.4295 | 0.7687 |
| All rows | 2.490 | 0.2859 |
| All rows | 2.023 | −0.6431 |
| All rows | −0.2138 | 0.5316 |
| All rows | −0.5985 | −0.4201 |
| All rows | 5.116 | −0.4794 |
| All rows | −0.1509 | −0.4802 |
| All rows | −0.8922 | −1.485 |
| All rows | −0.2440 | 0.1274 |
| All rows | 2.015 | 1.008 |
| All rows | −1.072 | −0.2194 |
| All rows | −0.1321 | −0.4667 |
| All rows | 0.6377 | −0.2038 |
| All rows | −0.8683 | −0.4693 |
| All rows | 0.9331 | −0.0149 |
| All rows | 0.9911 | 1.709 |
| All rows | −0.2035 | 1.373 |
| All rows | −2.617 | −0.5470 |
First 60 of 532 rows.
View data
| Part | Loss | Epoch |
|---|---|---|
| InfoNCE | 4.740 | 1 |
| InfoNCE | 4.729 | 2 |
| InfoNCE | 4.749 | 3 |
| InfoNCE | 4.769 | 4 |
| InfoNCE | 4.737 | 5 |
| InfoNCE | 4.726 | 6 |
| InfoNCE | 4.725 | 7 |
| InfoNCE | 4.734 | 8 |
| InfoNCE | 4.723 | 9 |
| InfoNCE | 4.720 | 10 |
| InfoNCE | 4.685 | 11 |
| InfoNCE | 4.730 | 12 |
| InfoNCE | 4.705 | 13 |
| InfoNCE | 4.703 | 14 |
| InfoNCE | 4.715 | 15 |
| InfoNCE | 4.675 | 16 |
| InfoNCE | 4.679 | 17 |
| InfoNCE | 4.677 | 18 |
| InfoNCE | 4.664 | 19 |
| InfoNCE | 4.667 | 20 |
| InfoNCE | 4.708 | 21 |
| InfoNCE | 4.690 | 22 |
| InfoNCE | 4.679 | 23 |
| InfoNCE | 4.640 | 24 |
| InfoNCE | 4.651 | 25 |
| InfoNCE | 4.657 | 26 |
| InfoNCE | 4.655 | 27 |
| InfoNCE | 4.642 | 28 |
| InfoNCE | 4.668 | 29 |
| InfoNCE | 4.637 | 30 |
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")
)
))
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.
Negatives that aren't negative
PredictPredict first
In a batch of 256 customer rows, SimCLR treats every other row as a negative for each anchor. Are they all truly different?
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.
Many negatives, cheaply: MoCo
ReadInfoNCE 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.What runs here
ReadCheck: contrastive learning
CheckpointCheck 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.
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