Skip to content

BYOL, SimSiam and DINO: learning without negatives

Drop the negatives and match two views directly, and the easy answer is to map everything to one point. BYOL and SimSiam avoid it with a predictor and a stopped gradient; DINO with a centered, sharpened teacher.

Advanced ~15 min12 steps

What runs in CodeSplash

You will be able to

  • Explain why matching two views without negatives invites collapse
  • Describe BYOL's predictor and momentum target, and SimSiam's stop-gradient
  • Train BYOL in Discover and read its target momentum and online–target gap
  • Describe DINO's centering and sharpening of the teacher's outputs
  • Check a negative-free representation for collapse and against raw columns

Read first

01

The trivial answer

Read

Contrastive learning needs negatives so that "make every row's views agree" can't be solved by giving every row the same vector. Remove the negatives and that constant answer has zero loss.

Self-supervised methods without negativesSelf-supervised learning without negativesObjectives that learn from two views of each row without contrasting it against other rows, and avoid collapse by other means. still work, because something in their design breaks the symmetry between the two sides. This lesson covers the teacher–student family: one side learns, the other provides a target it doesn't update by gradient.

02

BYOL: predict a slow target

Read

BYOLBYOLAn online network predicts a momentum target network's representation of another view; there are no negative rows. has an online network and a target network. The online side encodes one view, projects it, and adds a small predictor that tries to output the target network's projection of the other view. The target's weights are a momentumMomentum encoderA copy of the encoder whose weights trail the trained one as a slow moving average; it gives stable targets or keys. average of the online weights, and no gradient flows into it.

In the reference's example the normalized prediction misses the normalized target by a squared distance of 0.0143, and one momentum step moves the target's weights to (0.401, 0.201). The asymmetry, predictor on one side and slow target on the other, is what keeps it from collapsing in practice.

03

How slowly the target moves

Read

The target momentumTarget momentum (BYOL)How slowly BYOL's target network follows the trained one; τ rises from the chosen value to 1 by the last step. τ sets the pace. After every training step the target moves a share 1 − τ of the way toward the online weights, and τ rises on a cosine schedule from its base value (the paper's 0.996) to 1 at the last step, so the target settles as training ends.

04

BYOL on penguins

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

A BYOL encoder on SCARF's corrupted views turned 344 rows (6 features) into 6-dimensional representations (final BYOL loss 0.906); neighborhoods are kept with trustworthiness 0.971. A 5-nearest-neighbor probe recovers species for 98.5% of rows (98.8% on the raw columns).

Final BYOL loss
0.9058
Trustworthiness (k = 10)
0.9709
Alignment (lower = views closer)
0.1050
Uniformity (lower = more spread)
−0.0133
Online–target gap (lower = target caught up)
1.751
5-NN probe accuracy (species)
98.5%

Plots

Contrastive representation (principal components 1 and 2)Which rows group together, and how well separated are the groups?
View data
speciesComponent 1Component 2
Adelie1.770−0.6156
Adelie1.229−1.380
Adelie1.439−0.7349
Adelie2.2100.0940
Adelie1.189−0.8570
Adelie1.8650.3217
Adelie1.074−1.706
Adelie1.6280.8968
Adelie1.907−0.5097
Adelie1.868−0.0574
Adelie1.780−0.9932
Adelie1.479−1.415
Adelie1.187−1.567
Adelie1.7180.4455
Adelie1.3640.8955
Adelie1.128−1.504
Adelie1.316−0.6829
Adelie1.5931.076
Adelie0.9834−1.615
Adelie1.6720.8578
Adelie−1.090−1.233
Adelie0.14910.1289
Adelie−0.8719−0.7326
Adelie0.09100.4715
Adelie0.09290.0466
Adelie−0.9623−0.8505
Adelie0.32410.1995
Adelie−0.6302−0.6112
Adelie−1.149−1.366
Adelie0.00810.1290
Adelie−0.2299−1.558
Adelie0.0828−0.2195
Adelie−0.0130−0.8990
Adelie0.46780.0794
Adelie−0.2944−0.4424
Adelie0.31501.277
Adelie0.32510.7169
Adelie−0.1299−1.278
Adelie−0.2929−1.219
Adelie−0.24060.4829
Adelie−0.1977−1.304
Adelie0.69610.8680
Adelie−0.2618−1.007
Adelie0.53620.9600
Adelie−0.0328−1.214
Adelie−0.12610.8898
Adelie0.8960−0.3457
Adelie0.3977−0.9307
Adelie−0.5117−0.6703
Adelie0.45380.8516
Adelie−0.7930−0.6062
Adelie−0.01760.5891
Adelie−0.8214−0.6988
Adelie0.51201.056
Adelie−0.8669−0.7625
Adelie0.42210.5622
Adelie−0.8231−0.6220
Adelie0.33240.6968
Adelie−0.8811−0.9474
Adelie0.20020.8036

First 60 of 344 rows.

BYOL loss by epochIs the network still learning, and which part of its loss moves?
View data
PartLossEpoch
Prediction error5.1791
Prediction error4.6832
Prediction error4.1533
Prediction error3.5484
Prediction error2.8365
Prediction error2.1496
Prediction error1.6787
Prediction error1.3398
Prediction error1.1469
Prediction error1.03410
Prediction error0.900811
Prediction error0.845012
Prediction error0.819113
Prediction error0.795614
Prediction error0.812915
Prediction error0.753616
Prediction error0.827817
Prediction error0.780918
Prediction error0.800719
Prediction error0.846020
Prediction error0.901621
Prediction error0.859322
Prediction error0.908023
Prediction error0.977324
Prediction error0.939725
Prediction error0.907726
Prediction error0.905427
Prediction error0.909528
Prediction error0.942629
Prediction error0.905830

Assumptions

  • The representation uses several directions — The first principal direction holds 51% 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.5% 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 8a7a49a6ec29106f
# 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_byol/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

# %% byol on SCARF's views (torch for R, float64, one thread): the row and its corrupted copy, a loss without negatives
HIDDEN <- as.integer(unlist(c(32)))
EMB <- as.integer(6)
OBJECTIVE <- "byol"
TITLE <- cs_ssl_title(OBJECTIVE)
fit <- cs_deep_fit_ssl(  # twin of codesplash.deep.ssl.fit_ssl (objectives without negatives)
  X, groups, HIDDEN, EMB, OBJECTIVE,
  activation = "relu",
  corruption = 0.6,
  epochs = as.integer(30),
  lr = 0.001,
  batch_size = 64,
  weight_decay = 0,
  seed = 42,
  redundancy_weight = 0.005,
  vicreg_weights = c(25, 25, 1),
  prototypes = as.integer(16),
  swav_temperature = 0.1,
  swav_epsilon = 0.05,
  target_momentum = 0.996,  # tau_base: the target follows the online network after every step
  sinkhorn_iterations = as.integer(3)
)
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_byol/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)))
for (pt in fit$parts) hist[[pt[1]]] <- vapply(fit$history, function(h) h[[pt[1]]], 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)
values$target_gap <- fit$target_gap  # mean squared distance between the online and target unit projections
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 = ","))))
part_keys <- vapply(fit$parts, function(pt) pt[1], character(1))
part_labels <- vapply(fit$parts, function(pt) pt[2], character(1))
charts[[2]] <- cs_chart("training", "training-components", paste(TITLE, "loss by epoch"), list(
  x = cs_col("Epoch", rep(hist$epoch, length(part_keys)), "numeric"),
  value = cs_col("Loss", unlist(lapply(part_keys, function(k) hist[[k]])), "numeric"),
  component = cs_col("Part", rep(part_labels, each = nrow(hist)), "categorical", levels = part_labels)
))
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 %s encoder on SCARF's corrupted views turned %d rows (%d features) into %d-dimensional representations (final %s loss %.3f); neighborhoods are kept with trustworthiness %.3f.",
                   TITLE, length(rows), length(groups), EMB, TITLE, 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 = paste("Final", TITLE, "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")
statistics <- append(statistics, list(list(key = "target_gap", label = "Online–target gap (lower = target caught up)", value = values$target_gap)), after = 4L)
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 BYOL encoder on SCARF's corrupted views turned 344 rows (6 features) into 6-dimensional representations (final BYOL loss 0.906); neighborhoods are kept with trustworthiness 0.971. A 5-nearest-neighbor probe recovers species for 98.5% of rows (98.8% on the raw columns).

Final BYOL loss
0.9058
Trustworthiness (k = 10)
0.9709
Alignment (lower = views closer)
0.1050
Uniformity (lower = more spread)
−0.0133
Online–target gap (lower = target caught up)
1.751
5-NN probe accuracy (species)
98.5%

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.
  • Neighbors share the label at least as often as in the raw data — 5-nearest-neighbor accuracy for species: 98.5% 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 8a7a49a6ec29106f
# 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.deep import ssl as csssl  # twin of codesplashr::cs_deep_fit_ssl (objectives without negatives)
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_byol/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))

# %% byol on SCARF's views (PyTorch, float64, one thread): the row and its corrupted copy, a loss without negatives
HIDDEN = [int(u) for u in [32]]
EMB = 6
OBJECTIVE = "byol"
TITLE = csssl.TITLES[OBJECTIVE]
fit = csssl.fit_ssl(
    X, groups, HIDDEN, EMB, OBJECTIVE,
    activation="relu",
    corruption=0.6,
    epochs=30,
    lr=0.001,
    batch_size=64,
    weight_decay=0,
    seed=42,
    redundancy_weight=0.005,
    vicreg_weights=(25, 25, 1),
    prototypes=16,
    swav_temperature=0.1,
    swav_epsilon=0.05,
    sinkhorn_iterations=3,
    target_momentum=0.996,  # τ_base: the target follows the online network after every step
)
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_byol/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"]]})
for key, _ in fit["parts"]:
    history[key] = [h[key] 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)
values["target_gap"] = float(fit["target_gap"])  # mean squared distance between the online and target unit projections
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"]]
part_labels = [lab for _, lab in fit["parts"]]
charts.append(cs.chart("training", "training-components", f"{TITLE} loss by epoch", {
    "x": cs.col("Epoch", ep * len(part_labels), "numeric"),
    "value": cs.col("Loss", [h[key] for key, _ in fit["parts"] for h in fit["history"]], "numeric"),
    "component": cs.col("Part", [lab for lab in part_labels for _ in ep], "categorical", levels=part_labels),
}))
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 {TITLE} encoder on SCARF's corrupted views turned {len(rows)} rows ({len(groups)} features) into {EMB}-dimensional "
    f"representations (final {TITLE} 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": f"Final {TITLE} 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": "target_gap", "label": "Online–target gap (lower = target caught up)", "value": values["target_gap"]},
    ] +([{"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"},
    ],
})

Objective: BYOL uses the same encoder and SCARF views, with the default target momentum. The final loss over both directions is 0.906, on a scale from 0 to 8. The probe recovers the species for 98.5% of rows (98.8% on the raw columns), and the top component holds only 51.0% of the variance: no sign of collapse.

The online–target gapOnline–target gapMean squared distance between the online and target networks' unit-length projections of each row; 0 to 4, lower means caught up. is 1.75, on a scale from 0 to 4: in 180 steps at 0.996 the target has barely left its starting copy. For runs this short, try 0.99 or lower. Checkpoints save the target, so a stopped run resumes exactly.

05

SimSiam: stop the gradient

Read

SimSiamSimSiamA predictor maps one view's projection onto the other's, whose side gets no gradient; that stop-gradient alone prevents collapse. shows the momentum target isn't essential. Both views go through the same encoder; a predictor maps one view's output toward the other's, and the other side gets a stop-gradient: it is treated as a constant target. The loss is a symmetric negative cosine similarity:

L=−12[cos⁡(p1,sg(z2))+cos⁡(p2,sg(z1))].L = -\tfrac12\left[\cos\left(p_1, \mathrm{sg}(z_2)\right) + \cos\left(p_2, \mathrm{sg}(z_1)\right)\right].

The best possible value is −1. In the reference's example it is −0.986. Remove the stop-gradient and SimSiam collapses.

06

SimSiam on iris

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

A SimSiam encoder on SCARF's corrupted views turned 150 rows (4 features) into 4-dimensional representations (final SimSiam loss -0.922); neighborhoods are kept with trustworthiness 0.887. A 5-nearest-neighbor probe recovers species for 80.7% of rows (94.7% on the raw columns).

Final SimSiam loss
−0.9223
Trustworthiness (k = 10)
0.8870
Alignment (lower = views closer)
0.2593
Uniformity (lower = more spread)
−0.0568
5-NN probe accuracy (species)
80.7%

Plots

Contrastive representation (principal components 1 and 2)Which rows group together, and how well separated are the groups?
View data
speciesComponent 1Component 2
setosa0.47400.8543
setosa2.7170.2022
setosa2.4670.4771
setosa2.7780.3115
setosa0.26621.009
setosa−2.0451.074
setosa1.7050.7734
setosa1.0170.7581
setosa3.6170.2631
setosa2.4650.3699
setosa−0.94020.9259
setosa1.3520.8166
setosa3.0140.2290
setosa3.9300.3293
setosa−2.5511.015
setosa−3.9931.222
setosa−1.8391.140
setosa0.34520.8471
setosa−2.1430.8700
setosa−0.91201.170
setosa0.06770.6211
setosa−0.66801.074
setosa1.3981.121
setosa0.68440.5832
setosa1.1180.8151
setosa2.4120.1844
setosa0.68230.7443
setosa0.19870.8193
setosa0.67870.7037
setosa2.2190.4662
setosa2.3950.3177
setosa−0.07520.6438
setosa−1.8081.323
setosa−2.7201.234
setosa2.3200.3357
setosa2.0720.5185
setosa−0.21960.6980
setosa0.60101.045
setosa3.4590.3059
setosa0.81090.7293
setosa0.62820.8752
setosa4.979−0.0399
setosa2.9400.4341
setosa0.01080.8556
setosa−1.3171.151
setosa2.6820.2175
setosa−0.84521.164
setosa2.5420.4591
setosa−0.75370.9702
setosa1.5080.6316
versicolor−2.068−0.5268
versicolor−1.935−0.1794
versicolor−1.470−0.5791
versicolor1.309−0.5481
versicolor−0.8834−0.3293
versicolor−1.127−0.0727
versicolor−1.907−0.0578
versicolor1.933−0.1769
versicolor−1.273−0.4916
versicolor−0.1321−0.1211

First 60 of 150 rows.

SimSiam loss by epochIs the network still learning, and which part of its loss moves?
View data
PartLossEpoch
Negative cosine−0.41151
Negative cosine−0.54682
Negative cosine−0.54663
Negative cosine−0.56144
Negative cosine−0.59575
Negative cosine−0.62506
Negative cosine−0.63627
Negative cosine−0.64108
Negative cosine−0.65429
Negative cosine−0.670810
Negative cosine−0.694211
Negative cosine−0.690912
Negative cosine−0.661913
Negative cosine−0.714514
Negative cosine−0.733115
Negative cosine−0.760616
Negative cosine−0.773617
Negative cosine−0.803618
Negative cosine−0.772619
Negative cosine−0.801220
Negative cosine−0.800821
Negative cosine−0.833922
Negative cosine−0.826023
Negative cosine−0.862624
Negative cosine−0.854525
Negative cosine−0.849926
Negative cosine−0.858527
Negative cosine−0.869728
Negative cosine−0.866529
Negative cosine−0.906430
Negative cosine−0.884931
Negative cosine−0.902132
Negative cosine−0.891233
Negative cosine−0.858434
Negative cosine−0.916435
Negative cosine−0.917636
Negative cosine−0.907337
Negative cosine−0.900538
Negative cosine−0.912439
Negative cosine−0.922340

Assumptions

  • The representation uses several directions — The first principal direction holds 84% of the representation's variance.
  • Neighbors share the label at least as often as in the raw data — 5-nearest-neighbor accuracy for species: 80.7% on the representation vs 94.7% 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 31100d9a0476c0d8
# Dataset: ml_iris (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/iris_simsiam/out-r")
FEATURES <- c("sepal_length", "sepal_width", "petal_length", "petal_width")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    sepal_length = "numeric",
    sepal_width = "numeric",
    petal_length = "numeric",
    petal_width = "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 <- "species"
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.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

# %% simsiam on SCARF's views (torch for R, float64, one thread): the row and its corrupted copy, a loss without negatives
HIDDEN <- as.integer(unlist(c(16)))
EMB <- as.integer(4)
OBJECTIVE <- "simsiam"
TITLE <- cs_ssl_title(OBJECTIVE)
fit <- cs_deep_fit_ssl(  # twin of codesplash.deep.ssl.fit_ssl (objectives without negatives)
  X, groups, HIDDEN, EMB, OBJECTIVE,
  activation = "relu",
  corruption = 0.5,
  epochs = as.integer(40),
  lr = 0.005,
  batch_size = 64,
  weight_decay = 0,
  seed = 42,
  redundancy_weight = 0.005,
  vicreg_weights = c(25, 25, 1),
  prototypes = as.integer(16),
  swav_temperature = 0.1,
  swav_epsilon = 0.05,
  sinkhorn_iterations = as.integer(3)
)
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/iris_simsiam/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)))
for (pt in fit$parts) hist[[pt[1]]] <- vapply(fit$history, function(h) h[[pt[1]]], 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 = ","))))
part_keys <- vapply(fit$parts, function(pt) pt[1], character(1))
part_labels <- vapply(fit$parts, function(pt) pt[2], character(1))
charts[[2]] <- cs_chart("training", "training-components", paste(TITLE, "loss by epoch"), list(
  x = cs_col("Epoch", rep(hist$epoch, length(part_keys)), "numeric"),
  value = cs_col("Loss", unlist(lapply(part_keys, function(k) hist[[k]])), "numeric"),
  component = cs_col("Part", rep(part_labels, each = nrow(hist)), "categorical", levels = part_labels)
))
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 %s encoder on SCARF's corrupted views turned %d rows (%d features) into %d-dimensional representations (final %s loss %.3f); neighborhoods are kept with trustworthiness %.3f.",
                   TITLE, length(rows), length(groups), EMB, TITLE, 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 = paste("Final", TITLE, "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 SimSiam encoder on SCARF's corrupted views turned 150 rows (4 features) into 4-dimensional representations (final SimSiam loss -0.922); neighborhoods are kept with trustworthiness 0.887. A 5-nearest-neighbor probe recovers species for 80.7% of rows (94.7% on the raw columns).

Final SimSiam loss
−0.9223
Trustworthiness (k = 10)
0.8870
Alignment (lower = views closer)
0.2593
Uniformity (lower = more spread)
−0.0568
5-NN probe accuracy (species)
80.7%

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 84% of the representation's variance.
  • Neighbors share the label at least as often as in the raw data — 5-nearest-neighbor accuracy for species: 80.7% on the representation vs 94.7% 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 31100d9a0476c0d8
# Dataset: ml_iris (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.deep import ssl as csssl  # twin of codesplashr::cs_deep_fit_ssl (objectives without negatives)
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/iris_simsiam/out-python",
)
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "sepal_length": "numeric",
        "sepal_width": "numeric",
        "petal_length": "numeric",
        "petal_width": "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 = "species"
if LABEL:
    df[LABEL] = pd.read_parquet("tests/parity/fixtures/ml_iris.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))

# %% simsiam on SCARF's views (PyTorch, float64, one thread): the row and its corrupted copy, a loss without negatives
HIDDEN = [int(u) for u in [16]]
EMB = 4
OBJECTIVE = "simsiam"
TITLE = csssl.TITLES[OBJECTIVE]
fit = csssl.fit_ssl(
    X, groups, HIDDEN, EMB, OBJECTIVE,
    activation="relu",
    corruption=0.5,
    epochs=40,
    lr=0.005,
    batch_size=64,
    weight_decay=0,
    seed=42,
    redundancy_weight=0.005,
    vicreg_weights=(25, 25, 1),
    prototypes=16,
    swav_temperature=0.1,
    swav_epsilon=0.05,
    sinkhorn_iterations=3,
)
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/iris_simsiam/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"]]})
for key, _ in fit["parts"]:
    history[key] = [h[key] 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"]]
part_labels = [lab for _, lab in fit["parts"]]
charts.append(cs.chart("training", "training-components", f"{TITLE} loss by epoch", {
    "x": cs.col("Epoch", ep * len(part_labels), "numeric"),
    "value": cs.col("Loss", [h[key] for key, _ in fit["parts"] for h in fit["history"]], "numeric"),
    "component": cs.col("Part", [lab for lab in part_labels for _ in ep], "categorical", levels=part_labels),
}))
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 {TITLE} encoder on SCARF's corrupted views turned {len(rows)} rows ({len(groups)} features) into {EMB}-dimensional "
    f"representations (final {TITLE} 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": f"Final {TITLE} 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"},
    ],
})

Objective: SimSiam uses the same encoder and SCARF views as InfoNCE. The final loss is −0.922. The nearest-neighbor probe reaches 80.7%, against 94.7% on the raw columns, and the first principal component holds 83.7% of the variance.

A loss near −1 with a top share that high says the views agree mostly along one direction: partial collapse. Compare the InfoNCE run's share, 59.3% on penguins, and try a longer run or another objective before using this representation.

07

No negatives can still collapse

Predict

Predict first

A SimSiam run's loss is near its best value. Is the representation safe from collapse?

Without negatives the loss can't collapseCollapse is possible, fully or along a few directions
Reveal

No. A near-perfect agreement loss is exactly what a collapsed representation would show. Check the top component's share and a probe against raw columns; full collapse gives one point, partial collapse a line or a plane.

With no negatives at all, every embedding ends at the same point.

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.

08

DINO: a centered, sharpened teacher

Read

DINO frames it as self-distillationSelf-distillationA student network matches a momentum teacher's sharpened, centered outputs on other views; centering and sharpening prevent collapse.. A student and a momentum teacher each output a probability vector over many dimensions. The student, seeing small crops, matches the teacher's output on large crops by cross-entropy. Two tricks stop collapse:

  • centering: subtract a running mean from the teacher's outputs, so no one dimension wins every time;
  • sharpening: a low teacher temperature, so its outputs aren't uniform.

In the reference's example the sharpened, centered teacher puts 0.918 on one dimension, the student's cross-entropy is 1.286, and the center moves to (0.12, 0.23, 0.11).

09

DINO's descendant in CodeSplash

Read

CodeSplash doesn't train DINO. It does run DINOv2DINOv2A vision transformer trained without labels to give look-alike images similar vectors; the small model has 384 values.-small, a vision transformer trained this way, as a pretrained encoder for image columns: Image embeddings turns each image into a vector for maps, neighbors and clustering.

Method guide · embed.imagesImage embeddings, map and neighbors (DINOv2 or ResNet-50)Which images look alike? Turn each image into a vector with a pretrained network, map them and find each one's nearest neighbors.

Pretrained features carry their training data's view of what looks alike. Check them on your own images with a probe or known groups before trusting the neighbors.

10

What runs here

Read
11

Check: learning without negatives

Checkpoint

Check yourself

What keeps BYOL from collapsing to a constant, despite having no negatives?

Show the answer

Answer: a

The predictor and momentum target break the symmetry between the two sides. Collapse is avoided in practice, not ruled out by the loss.

Check yourself

How are BYOL's target network weights updated?

Show the answer

Answer: b

The target trails the online network slowly; no gradient flows into it.

Check yourself

Where can you train a BYOL representation of a table in CodeSplash?

Show the answer

Answer: a

BYOL is one of the Contrastive representation's objectives, in both engines, on the same encoder and corrupted views as SimSiam and InfoNCE.

Check yourself

A BYOL run on a table takes 180 steps with target momentum 0.996 and ends with a large online–target gap. What's the likely reading?

Show the answer

Answer: a

τ = 0.996 moves the target 0.4% of the way per step at the start, and less later. That suits runs of many thousands of steps. The gap measures lag, not quality: the probe and the top component's share judge the representation.

Check yourself

What happens to SimSiam if you remove the stop-gradient?

Show the answer

Answer: b

The stop-gradient is the piece that prevents the trivial solution in SimSiam; without it the loss is minimized by a constant output.

Check yourself

A SimSiam representation has a loss near −1 and its first principal component holds most of the variance. What's the reading?

Show the answer

Answer: a

A near-best loss is consistent with collapse. The top component's share and the probe against raw columns tell them apart.

Check yourself

In DINO, what does centering the teacher's outputs prevent?

Show the answer

Answer: a

Subtracting a running mean stops one dimension from dominating; sharpening stops the opposite failure, a uniform output. Together they avoid collapse.

Check yourself

What does CodeSplash do with DINO-style models?

Show the answer

Answer: b

The DINOv2-small encoder, trained with self-distillation, embeds images for maps and neighbors. Training DINO itself is explained here.

12

Recap

Recap
  • Without negatives, a constant representation has zero loss; designs must break the symmetry.
  • BYOL uses a predictor and a momentum target; SimSiam a predictor and a stop-gradient; DINO a centered, sharpened momentum teacher.
  • A near-best loss doesn't rule out collapse: check the top component's share and a probe against raw columns.
  • SimSiam and BYOL run in Discover; BYOL's target momentum rises to 1 on a cosine schedule, and a short run needs a lower base value. DINO runs only as the pretrained DINOv2 image encoder.

Concepts in this lesson