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.
What runs in CodeSplash
- DNN068Bootstrap Your Own Latent (BYOL) Runs in CodeSplash (Experimental)
- DNN069SimSiam Runs in CodeSplash (Experimental)
- DNN071Self-distillation with no labels (DINO) Partly runs in CodeSplash (Experimental)
- Contrastive representation (SCARF) Experimental
- Image embeddings, map and neighbors (DINOv2 or ResNet-50) Experimental
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
The trivial answer
ReadContrastive 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.
BYOL: predict a slow target
ReadBYOLBYOLAn 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.
How slowly the target moves
ReadThe 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.
BYOL on penguins
ExploreA 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
View data
| species | Component 1 | Component 2 |
|---|---|---|
| Adelie | 1.770 | −0.6156 |
| Adelie | 1.229 | −1.380 |
| Adelie | 1.439 | −0.7349 |
| Adelie | 2.210 | 0.0940 |
| Adelie | 1.189 | −0.8570 |
| Adelie | 1.865 | 0.3217 |
| Adelie | 1.074 | −1.706 |
| Adelie | 1.628 | 0.8968 |
| Adelie | 1.907 | −0.5097 |
| Adelie | 1.868 | −0.0574 |
| Adelie | 1.780 | −0.9932 |
| Adelie | 1.479 | −1.415 |
| Adelie | 1.187 | −1.567 |
| Adelie | 1.718 | 0.4455 |
| Adelie | 1.364 | 0.8955 |
| Adelie | 1.128 | −1.504 |
| Adelie | 1.316 | −0.6829 |
| Adelie | 1.593 | 1.076 |
| Adelie | 0.9834 | −1.615 |
| Adelie | 1.672 | 0.8578 |
| Adelie | −1.090 | −1.233 |
| Adelie | 0.1491 | 0.1289 |
| Adelie | −0.8719 | −0.7326 |
| Adelie | 0.0910 | 0.4715 |
| Adelie | 0.0929 | 0.0466 |
| Adelie | −0.9623 | −0.8505 |
| Adelie | 0.3241 | 0.1995 |
| Adelie | −0.6302 | −0.6112 |
| Adelie | −1.149 | −1.366 |
| Adelie | 0.0081 | 0.1290 |
| Adelie | −0.2299 | −1.558 |
| Adelie | 0.0828 | −0.2195 |
| Adelie | −0.0130 | −0.8990 |
| Adelie | 0.4678 | 0.0794 |
| Adelie | −0.2944 | −0.4424 |
| Adelie | 0.3150 | 1.277 |
| Adelie | 0.3251 | 0.7169 |
| Adelie | −0.1299 | −1.278 |
| Adelie | −0.2929 | −1.219 |
| Adelie | −0.2406 | 0.4829 |
| Adelie | −0.1977 | −1.304 |
| Adelie | 0.6961 | 0.8680 |
| Adelie | −0.2618 | −1.007 |
| Adelie | 0.5362 | 0.9600 |
| Adelie | −0.0328 | −1.214 |
| Adelie | −0.1261 | 0.8898 |
| Adelie | 0.8960 | −0.3457 |
| Adelie | 0.3977 | −0.9307 |
| Adelie | −0.5117 | −0.6703 |
| Adelie | 0.4538 | 0.8516 |
| Adelie | −0.7930 | −0.6062 |
| Adelie | −0.0176 | 0.5891 |
| Adelie | −0.8214 | −0.6988 |
| Adelie | 0.5120 | 1.056 |
| Adelie | −0.8669 | −0.7625 |
| Adelie | 0.4221 | 0.5622 |
| Adelie | −0.8231 | −0.6220 |
| Adelie | 0.3324 | 0.6968 |
| Adelie | −0.8811 | −0.9474 |
| Adelie | 0.2002 | 0.8036 |
First 60 of 344 rows.
View data
| Part | Loss | Epoch |
|---|---|---|
| Prediction error | 5.179 | 1 |
| Prediction error | 4.683 | 2 |
| Prediction error | 4.153 | 3 |
| Prediction error | 3.548 | 4 |
| Prediction error | 2.836 | 5 |
| Prediction error | 2.149 | 6 |
| Prediction error | 1.678 | 7 |
| Prediction error | 1.339 | 8 |
| Prediction error | 1.146 | 9 |
| Prediction error | 1.034 | 10 |
| Prediction error | 0.9008 | 11 |
| Prediction error | 0.8450 | 12 |
| Prediction error | 0.8191 | 13 |
| Prediction error | 0.7956 | 14 |
| Prediction error | 0.8129 | 15 |
| Prediction error | 0.7536 | 16 |
| Prediction error | 0.8278 | 17 |
| Prediction error | 0.7809 | 18 |
| Prediction error | 0.8007 | 19 |
| Prediction error | 0.8460 | 20 |
| Prediction error | 0.9016 | 21 |
| Prediction error | 0.8593 | 22 |
| Prediction error | 0.9080 | 23 |
| Prediction error | 0.9773 | 24 |
| Prediction error | 0.9397 | 25 |
| Prediction error | 0.9077 | 26 |
| Prediction error | 0.9054 | 27 |
| Prediction error | 0.9095 | 28 |
| Prediction error | 0.9426 | 29 |
| Prediction error | 0.9058 | 30 |
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")
)
))
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.
SimSiam: stop the gradient
ReadSimSiamSimSiamA 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:
The best possible value is −1. In the reference's example it is −0.986. Remove the stop-gradient and SimSiam collapses.
SimSiam on iris
ExploreA 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
View data
| species | Component 1 | Component 2 |
|---|---|---|
| setosa | 0.4740 | 0.8543 |
| setosa | 2.717 | 0.2022 |
| setosa | 2.467 | 0.4771 |
| setosa | 2.778 | 0.3115 |
| setosa | 0.2662 | 1.009 |
| setosa | −2.045 | 1.074 |
| setosa | 1.705 | 0.7734 |
| setosa | 1.017 | 0.7581 |
| setosa | 3.617 | 0.2631 |
| setosa | 2.465 | 0.3699 |
| setosa | −0.9402 | 0.9259 |
| setosa | 1.352 | 0.8166 |
| setosa | 3.014 | 0.2290 |
| setosa | 3.930 | 0.3293 |
| setosa | −2.551 | 1.015 |
| setosa | −3.993 | 1.222 |
| setosa | −1.839 | 1.140 |
| setosa | 0.3452 | 0.8471 |
| setosa | −2.143 | 0.8700 |
| setosa | −0.9120 | 1.170 |
| setosa | 0.0677 | 0.6211 |
| setosa | −0.6680 | 1.074 |
| setosa | 1.398 | 1.121 |
| setosa | 0.6844 | 0.5832 |
| setosa | 1.118 | 0.8151 |
| setosa | 2.412 | 0.1844 |
| setosa | 0.6823 | 0.7443 |
| setosa | 0.1987 | 0.8193 |
| setosa | 0.6787 | 0.7037 |
| setosa | 2.219 | 0.4662 |
| setosa | 2.395 | 0.3177 |
| setosa | −0.0752 | 0.6438 |
| setosa | −1.808 | 1.323 |
| setosa | −2.720 | 1.234 |
| setosa | 2.320 | 0.3357 |
| setosa | 2.072 | 0.5185 |
| setosa | −0.2196 | 0.6980 |
| setosa | 0.6010 | 1.045 |
| setosa | 3.459 | 0.3059 |
| setosa | 0.8109 | 0.7293 |
| setosa | 0.6282 | 0.8752 |
| setosa | 4.979 | −0.0399 |
| setosa | 2.940 | 0.4341 |
| setosa | 0.0108 | 0.8556 |
| setosa | −1.317 | 1.151 |
| setosa | 2.682 | 0.2175 |
| setosa | −0.8452 | 1.164 |
| setosa | 2.542 | 0.4591 |
| setosa | −0.7537 | 0.9702 |
| setosa | 1.508 | 0.6316 |
| versicolor | −2.068 | −0.5268 |
| versicolor | −1.935 | −0.1794 |
| versicolor | −1.470 | −0.5791 |
| versicolor | 1.309 | −0.5481 |
| versicolor | −0.8834 | −0.3293 |
| versicolor | −1.127 | −0.0727 |
| versicolor | −1.907 | −0.0578 |
| versicolor | 1.933 | −0.1769 |
| versicolor | −1.273 | −0.4916 |
| versicolor | −0.1321 | −0.1211 |
First 60 of 150 rows.
View data
| Part | Loss | Epoch |
|---|---|---|
| Negative cosine | −0.4115 | 1 |
| Negative cosine | −0.5468 | 2 |
| Negative cosine | −0.5466 | 3 |
| Negative cosine | −0.5614 | 4 |
| Negative cosine | −0.5957 | 5 |
| Negative cosine | −0.6250 | 6 |
| Negative cosine | −0.6362 | 7 |
| Negative cosine | −0.6410 | 8 |
| Negative cosine | −0.6542 | 9 |
| Negative cosine | −0.6708 | 10 |
| Negative cosine | −0.6942 | 11 |
| Negative cosine | −0.6909 | 12 |
| Negative cosine | −0.6619 | 13 |
| Negative cosine | −0.7145 | 14 |
| Negative cosine | −0.7331 | 15 |
| Negative cosine | −0.7606 | 16 |
| Negative cosine | −0.7736 | 17 |
| Negative cosine | −0.8036 | 18 |
| Negative cosine | −0.7726 | 19 |
| Negative cosine | −0.8012 | 20 |
| Negative cosine | −0.8008 | 21 |
| Negative cosine | −0.8339 | 22 |
| Negative cosine | −0.8260 | 23 |
| Negative cosine | −0.8626 | 24 |
| Negative cosine | −0.8545 | 25 |
| Negative cosine | −0.8499 | 26 |
| Negative cosine | −0.8585 | 27 |
| Negative cosine | −0.8697 | 28 |
| Negative cosine | −0.8665 | 29 |
| Negative cosine | −0.9064 | 30 |
| Negative cosine | −0.8849 | 31 |
| Negative cosine | −0.9021 | 32 |
| Negative cosine | −0.8912 | 33 |
| Negative cosine | −0.8584 | 34 |
| Negative cosine | −0.9164 | 35 |
| Negative cosine | −0.9176 | 36 |
| Negative cosine | −0.9073 | 37 |
| Negative cosine | −0.9005 | 38 |
| Negative cosine | −0.9124 | 39 |
| Negative cosine | −0.9223 | 40 |
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")
)
))
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.
No negatives can still collapse
PredictPredict first
A SimSiam run's loss is near its best value. Is the representation safe from collapse?
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?
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.
DINO: a centered, sharpened teacher
ReadDINO 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).
DINO's descendant in CodeSplash
ReadCodeSplash 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.
What runs here
ReadCheck: learning without negatives
CheckpointCheck 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.
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