Contrastive learning on video: CVRL and VideoMoCo
Two clips from one video should embed close together; clips from other videos, far apart. See how CVRL samples clips and augments them consistently, how VideoMoCo keeps a queue of negatives, and what positives and negatives get wrong.
What runs in CodeSplash
- VID022Contrastive Video Representation Learning (CVRL) Explained here
- VID023VideoMoCo Explained here
- Contrastive representation (SCARF) Experimental
You will be able to
- Build positive and negative pairs from video and write the contrastive loss
- Explain why augmentations must be applied consistently across a clip's frames
- Describe a momentum key encoder with a queue of negatives, and why old keys can mislead
- Name ways same-video positives and other-video negatives can be wrong
Positives from the same video
ReadContrastive learningContrastive learningLearning representations without labels by pulling two views of the same row together and pushing other rows' views away. needs pairs that should look alike. In video they come free: two clips sampled from the same video are a positive pair; clips from other videos are negatives. The encoder is trained so each clip's embedding is closer to its positive than to the others:
with the cosine similarity and a temperature. This is the InfoNCEInfoNCE lossA loss that asks each row to pick out its own corrupted view among the views of every row in the batch. loss from the generative and self-supervised track.
Positives pull together and negatives push apart; remove the negatives and see what happens.
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.
CVRL: sample and augment with care
ReadCVRL's contribution is in how the two clips are made. Their start times are drawn so nearby clips are more likely, and each clip's spatial augmentations (crop, color change) are applied identically to every frame in it. Changing the crop frame by frame would add jitter that looks like motion and corrupt what the encoder learns about movement.
In the reference's toy, a view and its slightly changed copy are scored against two unrelated views; the loss is 0.0078, small because the positive is by far the most similar.
Is the same video always the same thing?
PredictPredict first
A ten-minute cooking video: one clip shows chopping, another four minutes later shows plating. CVRL treats them as a positive pair. Do they show the same thing?
Reveal
Not always. Same-video positives can show different events, and different-video negatives can show the same action. Both kinds of mistake teach the encoder something wrong. Sampling clips close in time reduces the first; nothing in the loss fixes the second.
The same loss on a table
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"},
],
})
CodeSplash runs this loss family on table rows: two corrupted copies of each row are the positive pair, other rows the negatives. A nearest-neighbor probe on the learned representation guesses species correctly for 98.3% of penguins, against 98.8% on the standardized columns. Contrastive learning doesn't always beat the raw data; the probe tells you.
VideoMoCo: many negatives, carefully
ReadMore negatives usually help, but large batches of video are expensive. MoCo keeps 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. for keys, updated as a slow average of the query encoder, , and a queueQueue of negativesKeys from recent batches kept in a first-in, first-out list, so each query is compared with many negatives at once. of recent keys as negatives.
VideoMoCo adds two video ideas: an adversary that drops frames to make harder queries, and lower weight for older keys, which came from an older encoder. In the reference's toy, a momentum update moves the key to 0.25 and 0.75; illustrative age weights are 1, 0.95 and 0.9025.
How to judge it
Read- Evaluate by a linear probe, by fine-tuning and by nearest-neighbor retrieval, with identical feature extraction for every method compared.
- Test with missing frames if robustness to them is the claim, and separate the effect of adversarial dropping from the queue's age weighting.
- Don't let validation labels decide which videos go into pretraining.
- Dropping frames can change what action a clip shows: a "view" isn't always harmless.
What runs here
Read| Entry | In CodeSplash |
|---|---|
| VID022 · Contrastive Video Representation Learning | Explained here |
| VID023 · VideoMoCo | Explained here |
Check: contrastive video learning
CheckpointCheck yourself
Why does CVRL apply the same crop and color change to every frame of a clip?
Show the answer
Answer: b
Consistent augmentation across frames keeps real motion intact while varying appearance.
Check yourself
In CVRL, what is a positive pair?
Show the answer
Answer: a
Same video, two clips; other videos supply negatives. No labels are used.
Check yourself
Two contrastive video methods are compared by linear probe. What makes the comparison fair?
Show the answer
Answer: b
Differences in extraction can matter as much as the pretraining method.
Check yourself
What does a MoCo-style queue provide?
Show the answer
Answer: b
Recent keys are reused as negatives, so each query sees many of them cheaply.
Check yourself
Why does VideoMoCo give older keys in the queue less weight?
Show the answer
Answer: a
The key encoder keeps changing; very old keys describe a different representation.
Check yourself
VideoMoCo makes harder views by dropping frames. When can that backfire?
Show the answer
Answer: b
A short action can disappear entirely. Check robustness claims on clips where it matters.
Recap
Recap- Clips from one video are positives, other videos negatives; the loss is InfoNCE.
- CVRL samples nearby clips and augments every frame of a clip the same way.
- VideoMoCo keeps a momentum encoder and a queue of negatives, down-weighting stale keys.
- Same-video positives and other-video negatives can both be wrong; judge with matched probes and retrieval.
Concepts in this lesson