Skip to content

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.

Advanced ~13 min9 steps

What runs in CodeSplash

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

Read first

01

Positives from the same video

Read

Contrastive 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 ziz_i is closer to its positive zi+z_i^+ than to the others:

Li=−log⁡es(zi,zi+)/τ∑j≠ies(zi,zj)/τ,L_i = -\log \frac{e^{s(z_i, z_i^+)/\tau}}{\sum_{j \ne i} e^{s(z_i, z_j)/\tau}},

with ss the cosine similarity and τ\tau 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?

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

CVRL: sample and augment with care

Read
Reference · VID022 · Explained hereContrastive Video Representation Learning (CVRL)Learns by bringing augmented views from the same video together and separating views from other videos. The important video-specific contribution is how temporal sampling and spatial augmentations preserve coherent…

CVRL'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.

03

Is the same video always the same thing?

Predict

Predict 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?

Yes: same video, same contentNot always: a long video can change activity between the two clipsOnly if the clips overlap
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.

04

The same loss on a table

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"},
    ],
})

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.

05

VideoMoCo: many negatives, carefully

Read
Reference · VID023 · Explained hereVideoMoCoAdapts momentum contrast to video with temporally adversarial examples and a queue designed to account for feature age.

More 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, θk←mθk+(1−m)θq\theta_k \leftarrow m\theta_k + (1 - m)\theta_q, 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.

06

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.
07

What runs here

Read
EntryIn CodeSplash
VID022 · Contrastive Video Representation LearningExplained here
VID023 · VideoMoCoExplained here
08

Check: contrastive video learning

Checkpoint

Check 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.

09

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