Representations without negatives: SimSiam, BYOL, Barlow Twins, VICReg and SwAV
The contrastive encoder can swap InfoNCE for five objectives that never compare a row with other rows. What each one does to avoid collapse, which numbers show it worked, and why a label probe still decides.
What runs in CodeSplash
- Contrastive representation (SCARF) Experimental
You will be able to
- Say why a two-view objective without negatives risks collapse, and how each of the five avoids it
- Read Barlow Twins' cross-correlation and VICReg's loss parts
- Compare objectives with the label probe and top_pc_share, not their loss values
Two views, no negatives
ReadThe contrastive encoder pairs each row with a corrupted copy and, with InfoNCE, asks it to pick its own copy out of the batch. The other rows are the negatives. Without them, an encoder could map every row to one point: both views would agree perfectly. That is collapse.
The Objective option offers five ways to learn from two views without negatives, each with its own guard against collapse (self-supervised learning 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.).
| Objective | What stops collapse |
|---|---|
| SimSiam | A predictor on one side and no gradient on the other |
| BYOL | A predictor and a slow target copy |
| Barlow Twins | Coordinates must not repeat each other |
| VICReg | Each coordinate must keep a spread across the batch |
| SwAV | Rows must spread evenly over learned prototypes |
BYOL: a slowly moving target
ReadBYOLBYOLAn online network predicts a momentum target network's representation of another view; there are no negative rows. predicts, from one view, what a target copy of the encoder makes of the other view. The target gets no gradient: after every step it moves a small share of the way toward the trained encoder, set by Target momentum. On the penguins with the default 0.996, the probe recovers the species for 98.5% of rows.
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
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"},
],
})
Has the target caught up?
PredictPredict first
That run takes 180 steps. Where does the online–target gap end, on its scale from 0 to 4?
Reveal
Well above 0: 1.75. At 0.996 the target moves 0.4% of the way per step, which suits runs of many thousands of steps. 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. measures lag, not quality; for short runs, try a target momentum of 0.99 or lower.
Barlow Twins: the cross-correlation
ReadBarlow TwinsBarlow TwinsPushes the two views' cross-correlation matrix toward the identity, so matching coordinates agree and different ones carry new information. standardizes each projection coordinate over the batch and correlates the row's view with the corrupted view. It wants 1 on the diagonal and 0 elsewhere.
A Barlow Twins encoder on SCARF's corrupted views turned 344 rows (6 features) into 6-dimensional representations (final Barlow Twins loss 1.835); neighborhoods are kept with trustworthiness 0.981. A 5-nearest-neighbor probe recovers species for 98.3% of rows (98.8% on the raw columns).
- Final Barlow Twins loss
- 1.835
- Trustworthiness (k = 10)
- 0.9812
- Alignment (lower = views closer)
- 0.6115
- Uniformity (lower = more spread)
- −0.9184
- 5-NN probe accuracy (species)
- 98.3%
Plots
View data
| species | Component 1 | Component 2 |
|---|---|---|
| Adelie | −2.667 | 0.6638 |
| Adelie | −2.590 | −0.4646 |
| Adelie | −2.359 | −0.3688 |
| Adelie | −1.452 | −0.1007 |
| Adelie | −2.828 | 0.1523 |
| Adelie | −2.616 | 1.229 |
| Adelie | −2.926 | −0.4506 |
| Adelie | −1.871 | 1.512 |
| Adelie | −2.655 | 0.1348 |
| Adelie | −2.204 | 0.5448 |
| Adelie | −2.589 | −0.3359 |
| Adelie | −2.809 | −0.4170 |
| Adelie | −2.825 | −0.5589 |
| Adelie | −2.613 | 1.531 |
| Adelie | −2.509 | 2.058 |
| Adelie | −3.030 | −0.2977 |
| Adelie | −2.504 | −0.0343 |
| Adelie | −1.603 | 1.597 |
| Adelie | −3.512 | −0.0996 |
| Adelie | −1.552 | 1.595 |
| Adelie | −2.177 | −0.1310 |
| Adelie | −1.720 | 0.6069 |
| Adelie | −1.323 | −0.2082 |
| Adelie | −1.083 | 0.5147 |
| Adelie | −1.348 | 0.5295 |
| Adelie | −1.404 | −0.1372 |
| Adelie | −1.494 | 0.3430 |
| Adelie | −1.468 | −0.3947 |
| Adelie | −2.369 | −0.1052 |
| Adelie | −1.270 | 0.3650 |
| Adelie | −2.552 | −0.6032 |
| Adelie | −2.159 | 0.6569 |
| Adelie | −2.315 | −0.3980 |
| Adelie | −1.676 | 0.3906 |
| Adelie | −1.816 | −0.1410 |
| Adelie | −1.052 | 1.475 |
| Adelie | −1.584 | 1.001 |
| Adelie | −2.182 | −0.5812 |
| Adelie | −2.844 | −0.0969 |
| Adelie | −0.9521 | 0.8477 |
| Adelie | −2.903 | −0.2148 |
| Adelie | −1.085 | 0.4253 |
| Adelie | −2.798 | −0.0150 |
| Adelie | −0.2010 | 0.6722 |
| Adelie | −2.586 | −0.3675 |
| Adelie | −0.7489 | 0.9444 |
| Adelie | −2.360 | 0.2019 |
| Adelie | −2.866 | −0.1937 |
| Adelie | −2.223 | −0.0333 |
| Adelie | −1.047 | 1.170 |
| Adelie | −1.255 | −0.4222 |
| Adelie | −0.5330 | 0.4830 |
| Adelie | −1.350 | −0.2315 |
| Adelie | 0.0166 | 0.2981 |
| Adelie | −1.955 | −0.0738 |
| Adelie | −0.8289 | 0.1475 |
| Adelie | −1.207 | −0.4279 |
| Adelie | −0.6531 | 0.1936 |
| Adelie | −2.001 | −0.1691 |
| Adelie | −0.8375 | 0.4265 |
First 60 of 344 rows.
View data
| Part | Loss | Epoch |
|---|---|---|
| On-diagonal | 3.487 | 1 |
| On-diagonal | 3.236 | 2 |
| On-diagonal | 3.967 | 3 |
| On-diagonal | 2.659 | 4 |
| On-diagonal | 2.873 | 5 |
| On-diagonal | 2.599 | 6 |
| On-diagonal | 2.908 | 7 |
| On-diagonal | 2.686 | 8 |
| On-diagonal | 2.474 | 9 |
| On-diagonal | 2.343 | 10 |
| On-diagonal | 2.550 | 11 |
| On-diagonal | 2.446 | 12 |
| On-diagonal | 2.157 | 13 |
| On-diagonal | 2.143 | 14 |
| On-diagonal | 2.493 | 15 |
| On-diagonal | 1.973 | 16 |
| On-diagonal | 1.689 | 17 |
| On-diagonal | 1.761 | 18 |
| On-diagonal | 1.763 | 19 |
| On-diagonal | 1.874 | 20 |
| On-diagonal | 1.979 | 21 |
| On-diagonal | 1.556 | 22 |
| On-diagonal | 1.745 | 23 |
| On-diagonal | 1.622 | 24 |
| On-diagonal | 2.081 | 25 |
| On-diagonal | 1.266 | 26 |
| On-diagonal | 1.986 | 27 |
| On-diagonal | 1.445 | 28 |
| On-diagonal | 1.523 | 29 |
| On-diagonal | 1.463 | 30 |
| Off-diagonal (× λ) | 0.0470 | 1 |
| Off-diagonal (× λ) | 0.0644 | 2 |
| Off-diagonal (× λ) | 0.0540 | 3 |
| Off-diagonal (× λ) | 0.0978 | 4 |
| Off-diagonal (× λ) | 0.1040 | 5 |
| Off-diagonal (× λ) | 0.1250 | 6 |
| Off-diagonal (× λ) | 0.0963 | 7 |
| Off-diagonal (× λ) | 0.1288 | 8 |
| Off-diagonal (× λ) | 0.1334 | 9 |
| Off-diagonal (× λ) | 0.1594 | 10 |
| Off-diagonal (× λ) | 0.1369 | 11 |
| Off-diagonal (× λ) | 0.1590 | 12 |
| Off-diagonal (× λ) | 0.1775 | 13 |
| Off-diagonal (× λ) | 0.1877 | 14 |
| Off-diagonal (× λ) | 0.1648 | 15 |
| Off-diagonal (× λ) | 0.2131 | 16 |
| Off-diagonal (× λ) | 0.2959 | 17 |
| Off-diagonal (× λ) | 0.2901 | 18 |
| Off-diagonal (× λ) | 0.2596 | 19 |
| Off-diagonal (× λ) | 0.2448 | 20 |
| Off-diagonal (× λ) | 0.2311 | 21 |
| Off-diagonal (× λ) | 0.3203 | 22 |
| Off-diagonal (× λ) | 0.2590 | 23 |
| Off-diagonal (× λ) | 0.3019 | 24 |
| Off-diagonal (× λ) | 0.2396 | 25 |
| Off-diagonal (× λ) | 0.3966 | 26 |
| Off-diagonal (× λ) | 0.2669 | 27 |
| Off-diagonal (× λ) | 0.3537 | 28 |
| Off-diagonal (× λ) | 0.3441 | 29 |
| Off-diagonal (× λ) | 0.3723 | 30 |
Projection coordinates of every row against those of its corrupted view, each standardized over the rows. Barlow Twins pushes the diagonal toward 1 and the rest toward 0.
View data
| Corrupted view | r | Row | Correlation |
|---|---|---|---|
| z1 | 0.54 | z1 | 0.5351 |
| z2 | 0.45 | z1 | 0.4508 |
| z3 | -0.47 | z1 | −0.4696 |
| z4 | -0.55 | z1 | −0.5505 |
| z5 | 0.48 | z1 | 0.4819 |
| z6 | 0.54 | z1 | 0.5354 |
| z1 | 0.51 | z2 | 0.5140 |
| z2 | 0.47 | z2 | 0.4665 |
| z3 | -0.45 | z2 | −0.4488 |
| z4 | -0.52 | z2 | −0.5204 |
| z5 | 0.44 | z2 | 0.4419 |
| z6 | 0.52 | z2 | 0.5208 |
| z1 | -0.45 | z3 | −0.4518 |
| z2 | -0.36 | z3 | −0.3611 |
| z3 | 0.49 | z3 | 0.4909 |
| z4 | 0.50 | z3 | 0.4964 |
| z5 | -0.50 | z3 | −0.5009 |
| z6 | -0.45 | z3 | −0.4477 |
| z1 | -0.52 | z4 | −0.5250 |
| z2 | -0.43 | z4 | −0.4318 |
| z3 | 0.49 | z4 | 0.4894 |
| z4 | 0.55 | z4 | 0.5524 |
| z5 | -0.51 | z4 | −0.5065 |
| z6 | -0.52 | z4 | −0.5228 |
| z1 | 0.46 | z5 | 0.4620 |
| z2 | 0.36 | z5 | 0.3583 |
| z3 | -0.49 | z5 | −0.4926 |
| z4 | -0.51 | z5 | −0.5096 |
| z5 | 0.51 | z5 | 0.5138 |
| z6 | 0.45 | z5 | 0.4548 |
| z1 | 0.53 | z6 | 0.5349 |
| z2 | 0.45 | z6 | 0.4547 |
| z3 | -0.47 | z6 | −0.4672 |
| z4 | -0.55 | z6 | −0.5489 |
| z5 | 0.48 | z6 | 0.4769 |
| z6 | 0.54 | z6 | 0.5371 |
Assumptions
- The representation uses several directions — The first principal direction holds 78% of the representation's variance.
- Neighbors share the label at least as often as in the raw data — 5-nearest-neighbor accuracy for species: 98.3% on the representation vs 98.8% on the standardized columns.
The exact R script · R R version 4.5.1 (2025-06-13)
# Contrastive representation (SCARF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.contrastive 1.3.0 · spec 740455f399dd7786
# 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_barlow/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
# %% barlow 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 <- "barlow"
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.05,
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/penguins_barlow/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)
for (pt in fit$parts) values[[sprintf("loss_part[%s]", pt[1])]] <- fit$final_parts[[pt[1]]] # last epoch's mean, weighted as in the loss
ccs <- cs_ssl_cross_corr_summary(fit$cross_corr)
values$cc_diag_mean <- ccs[1]
values$cc_offdiag_rms <- ccs[2]
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)
))
C <- fit$cross_corr
dims <- paste0("z", seq_len(EMB))
charts[[length(charts) + 1L]] <- cs_chart("cross_correlation", "matrix-heatmap", "Cross-correlation of the two views (Barlow Twins)", list(
row = cs_col("Row", rep(dims, each = EMB), "categorical", levels = dims),
col = cs_col("Corrupted view", rep(dims, times = EMB), "categorical", levels = dims),
value = cs_col("Correlation", as.numeric(t(C)), "numeric"),
label = cs_col("r", sprintf("%.2f", as.numeric(t(C))), "categorical")
), controls = list(scale = "diverging", min = -1, max = 1),
note = "Projection coordinates of every row against those of its corrupted view, each standardized over the rows. Barlow Twins pushes the diagonal toward 1 and the rest toward 0.")
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 Barlow Twins encoder on SCARF's corrupted views turned 344 rows (6 features) into 6-dimensional representations (final Barlow Twins loss 1.835); neighborhoods are kept with trustworthiness 0.981. A 5-nearest-neighbor probe recovers species for 98.3% of rows (98.8% on the raw columns).
- Final Barlow Twins loss
- 1.835
- Trustworthiness (k = 10)
- 0.9812
- Alignment (lower = views closer)
- 0.6115
- Uniformity (lower = more spread)
- −0.9184
- 5-NN probe accuracy (species)
- 98.3%
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- The representation uses several directions — The first principal direction holds 78% of the representation's variance.
- Neighbors share the label at least as often as in the raw data — 5-nearest-neighbor accuracy for species: 98.3% on the representation vs 98.8% on the standardized columns.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Contrastive representation (SCARF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.contrastive 1.3.0 · spec 740455f399dd7786
# 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_barlow/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))
# %% barlow 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 = "barlow"
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.05,
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/penguins_barlow/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)
for key, _ in fit["parts"]:
values[f"loss_part[{key}]"] = float(fit["final_parts"][key]) # last epoch's mean, weighted as in the loss
values["cc_diag_mean"], values["cc_offdiag_rms"] = csssl.cross_corr_summary(fit["cross_corr"])
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),
}))
C = fit["cross_corr"]
dims = [f"z{j + 1}" for j in range(EMB)]
charts.append(cs.chart("cross_correlation", "matrix-heatmap", "Cross-correlation of the two views (Barlow Twins)", {
"row": cs.col("Row", [d for d in dims for _ in dims], "categorical", levels=dims),
"col": cs.col("Corrupted view", [d for _ in dims for d in dims], "categorical", levels=dims),
"value": cs.col("Correlation", C.ravel().tolist(), "numeric"),
"label": cs.col("r", [f"{c:.2f}" for c in C.ravel()], "categorical"),
}, controls={"scale": "diverging", "min": -1, "max": 1},
note="Projection coordinates of every row against those of its corrupted view, each standardized over the rows. Barlow Twins pushes the diagonal toward 1 and the rest toward 0."))
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"},
],
})
How close to the identity?
PredictPredict first
After 30 epochs on the penguins, where is the mean of the diagonal of the cross-correlation over all rows?
Reveal
About halfway: 0.516, with off-diagonal cells at 0.483 (root mean square). The corrupted view replaces a share of each row's features, so it can't match perfectly. Still, the 5-nearest-neighbor probe recovers the species for 98.3% of rows.
VICReg: three parts of one loss
ReadVICRegVICRegThree terms: views stay close (invariance), each coordinate keeps a spread near 1 (variance), coordinates stay uncorrelated (covariance). adds an invariance term (views close), a variance term (each coordinate's spread near 1) and a covariance term (coordinates uncorrelated). The VICReg loss by epoch chart draws the three loss partsLoss partsThe pieces a self-supervised loss adds up, each as the last epoch's mean: Barlow's on- and off-diagonal, VICReg's three terms..
A VICReg encoder on SCARF's corrupted views turned 532 rows (7 features) into 6-dimensional representations (final VICReg loss 19.341); neighborhoods are kept with trustworthiness 0.903.
- Final VICReg loss
- 19.341
- Trustworthiness (k = 10)
- 0.9029
- Alignment (lower = views closer)
- 0.5058
- Uniformity (lower = more spread)
- −0.9277
Plots
View data
| Group | Component 1 | Component 2 |
|---|---|---|
| All rows | −1.597 | 0.5530 |
| All rows | −0.0038 | 0.6966 |
| All rows | 0.6302 | −0.7124 |
| All rows | −0.7062 | −1.917 |
| All rows | −1.576 | 1.132 |
| All rows | 2.531 | 0.0242 |
| All rows | −1.683 | 0.5129 |
| All rows | −0.2784 | 0.3678 |
| All rows | 3.643 | 0.7543 |
| All rows | 0.7746 | −1.871 |
| All rows | 3.643 | −1.323 |
| All rows | −0.0477 | 0.3270 |
| All rows | 0.5134 | 0.4486 |
| All rows | 3.320 | 1.006 |
| All rows | 0.2628 | −1.504 |
| All rows | 0.0272 | 1.465 |
| All rows | 2.374 | 1.190 |
| All rows | 1.104 | −0.5184 |
| All rows | −0.3778 | 0.1996 |
| All rows | −1.158 | 1.385 |
| All rows | 0.8915 | 1.558 |
| All rows | 1.342 | 0.0735 |
| All rows | 2.005 | 1.077 |
| All rows | −0.3010 | 1.675 |
| All rows | −0.8806 | 0.0816 |
| All rows | 0.1246 | −0.5521 |
| All rows | 0.7056 | 1.561 |
| All rows | −0.7581 | −0.0886 |
| All rows | −1.223 | −0.7130 |
| All rows | −0.3729 | 0.2543 |
| All rows | −0.5049 | −0.4853 |
| All rows | −1.447 | 0.3746 |
| All rows | −0.8827 | −0.0638 |
| All rows | −0.9652 | 0.5929 |
| All rows | −0.2871 | −0.7429 |
| All rows | 2.846 | 1.180 |
| All rows | 0.5066 | 1.459 |
| All rows | 0.1438 | 1.529 |
| All rows | 2.422 | 1.008 |
| All rows | −1.205 | 0.3001 |
| All rows | 1.036 | −0.5587 |
| All rows | 1.909 | 0.7541 |
| All rows | 0.2110 | 0.8283 |
| All rows | −0.1185 | 1.614 |
| All rows | −0.7421 | 0.2332 |
| All rows | −1.132 | 0.4431 |
| All rows | −1.783 | −0.3311 |
| All rows | 4.960 | 0.4781 |
| All rows | −1.754 | 0.0779 |
| All rows | −0.6006 | −2.253 |
| All rows | −0.1966 | 1.179 |
| All rows | −0.8381 | 1.073 |
| All rows | −0.4826 | −0.1608 |
| All rows | −1.556 | −0.1042 |
| All rows | −1.544 | 0.4449 |
| All rows | 1.280 | 0.5802 |
| All rows | −1.192 | 0.4690 |
| All rows | 0.0822 | 0.8861 |
| All rows | −1.401 | 0.2451 |
| All rows | 0.9145 | −1.853 |
First 60 of 532 rows.
View data
| Part | Loss | Epoch |
|---|---|---|
| Invariance | 8.675 | 1 |
| Invariance | 4.981 | 2 |
| Invariance | 3.933 | 3 |
| Invariance | 3.252 | 4 |
| Invariance | 3.723 | 5 |
| Invariance | 4.099 | 6 |
| Invariance | 4.601 | 7 |
| Invariance | 4.870 | 8 |
| Invariance | 5.496 | 9 |
| Invariance | 5.205 | 10 |
| Invariance | 5.127 | 11 |
| Invariance | 4.943 | 12 |
| Invariance | 4.608 | 13 |
| Invariance | 5.097 | 14 |
| Invariance | 6.222 | 15 |
| Invariance | 5.763 | 16 |
| Invariance | 5.668 | 17 |
| Invariance | 6.177 | 18 |
| Invariance | 5.958 | 19 |
| Invariance | 5.954 | 20 |
| Variance | 12.678 | 1 |
| Variance | 15.483 | 2 |
| Variance | 16.740 | 3 |
| Variance | 17.296 | 4 |
| Variance | 16.881 | 5 |
| Variance | 16.430 | 6 |
| Variance | 15.467 | 7 |
| Variance | 14.797 | 8 |
| Variance | 14.568 | 9 |
| Variance | 14.599 | 10 |
| Variance | 14.791 | 11 |
| Variance | 14.933 | 12 |
| Variance | 14.904 | 13 |
| Variance | 14.665 | 14 |
| Variance | 13.687 | 15 |
| Variance | 13.761 | 16 |
| Variance | 13.313 | 17 |
| Variance | 12.917 | 18 |
| Variance | 12.852 | 19 |
| Variance | 13.128 | 20 |
| Covariance | 0.5866 | 1 |
| Covariance | 0.1613 | 2 |
| Covariance | 0.0699 | 3 |
| Covariance | 0.0456 | 4 |
| Covariance | 0.0543 | 5 |
| Covariance | 0.0697 | 6 |
| Covariance | 0.1083 | 7 |
| Covariance | 0.1418 | 8 |
| Covariance | 0.1630 | 9 |
| Covariance | 0.1484 | 10 |
| Covariance | 0.1321 | 11 |
| Covariance | 0.1218 | 12 |
| Covariance | 0.1199 | 13 |
| Covariance | 0.1302 | 14 |
| Covariance | 0.1829 | 15 |
| Covariance | 0.1851 | 16 |
| Covariance | 0.2121 | 17 |
| Covariance | 0.2471 | 18 |
| Covariance | 0.2632 | 19 |
| Covariance | 0.2587 | 20 |
Assumptions
- The representation uses several directions — The first principal direction holds 46% of the representation's variance.
The exact R script · R R version 4.5.1 (2025-06-13)
# Contrastive representation (SCARF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.contrastive 1.3.0 · spec 60a07fe0f3bfc7c5
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_deep_fit_scarf: SCARF contrastive encoder (twin of codesplash.deep.generative)
# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE <- "median"
SCALE <- "standard"
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/discover.contrastive/pima_vicreg/out-r")
FEATURES <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
df, FEATURES,
kinds = list(
npreg = "numeric",
glu = "numeric",
bp = "numeric",
skin = "numeric",
bmi = "numeric",
ped = "numeric",
age = "numeric"
),
levels = list(
),
impute = IMPUTE,
scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df)) # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
LABEL <- NULL
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = LABEL))[[LABEL]]
groups <- cs_deep_feature_groups(fitted) # design columns of each feature: corruption swaps whole features
if (length(rows) < 3L) cs_error("CS_E_TOO_FEW_ROWS", what = "Contrastive representation", min = 3L, n = length(rows)) # map, trustworthiness, probe
# %% vicreg 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(24)))
EMB <- as.integer(6)
OBJECTIVE <- "vicreg"
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(20),
lr = 0.002,
batch_size = 128,
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/pima_vicreg/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)
for (pt in fit$parts) values[[sprintf("loss_part[%s]", pt[1])]] <- fit$final_parts[[pt[1]]] # last epoch's mean, weighted as in the loss
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 VICReg encoder on SCARF's corrupted views turned 532 rows (7 features) into 6-dimensional representations (final VICReg loss 19.341); neighborhoods are kept with trustworthiness 0.903.
- Final VICReg loss
- 19.341
- Trustworthiness (k = 10)
- 0.9029
- Alignment (lower = views closer)
- 0.5059
- Uniformity (lower = more spread)
- −0.9277
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 46% of the representation's variance.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Contrastive representation (SCARF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.contrastive 1.3.0 · spec 60a07fe0f3bfc7c5
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.deep import generative as gen # twin of codesplashr::cs_deep_fit_scarf (shared weights and corruption draws)
from codesplash.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/pima_vicreg/out-python",
)
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"npreg": "numeric",
"glu": "numeric",
"bp": "numeric",
"skin": "numeric",
"bmi": "numeric",
"ped": "numeric",
"age": "numeric",
},
levels={
},
impute=IMPUTE,
scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df) # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
LABEL = None
if LABEL:
df[LABEL] = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=[LABEL])[LABEL]
groups = gen.feature_groups(fitted) # design columns of each feature: corruption swaps whole features
if len(rows) < 3: # the map, trustworthiness (k = n − 2) and the probe need three rows
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Contrastive representation", min=3, n=len(rows))
# %% vicreg on SCARF's views (PyTorch, float64, one thread): the row and its corrupted copy, a loss without negatives
HIDDEN = [int(u) for u in [24]]
EMB = 6
OBJECTIVE = "vicreg"
TITLE = csssl.TITLES[OBJECTIVE]
fit = csssl.fit_ssl(
X, groups, HIDDEN, EMB, OBJECTIVE,
activation="relu",
corruption=0.6,
epochs=20,
lr=0.002,
batch_size=128,
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/pima_vicreg/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)
for key, _ in fit["parts"]:
values[f"loss_part[{key}]"] = float(fit["final_parts"][key]) # last epoch's mean, weighted as in the loss
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"},
],
})
Which part is largest?
PredictPredict first
On the Pima rows after 20 epochs, which part is largest?
Reveal
Variance, at 13.1 of 19.3: many coordinates still spread less than 1 across the batch. Invariance is 5.95 and covariance 0.259. More epochs would push the variance term down.
Comparing objectives
ReadLosses of different objectives aren't on one scale, so compare the checks every run reports. On iris, the SimSiam encoder's probe recovers the species for 80.7% of rows, below the raw columns' 94.7%, and its first principal direction holds 83.7% of the variance. SwAVSwAVRows are assigned to learned prototypes in balanced groups, and each view must predict the group the other view was given. reaches 95.3% and keeps 4 prototypes in use. Each row's prototype is saved with its representation.
A SwAV encoder on SCARF's corrupted views turned 150 rows (4 features) into 4-dimensional representations (final SwAV loss 1.973); neighborhoods are kept with trustworthiness 0.956. A 5-nearest-neighbor probe recovers species for 95.3% of rows (94.7% on the raw columns).
- Final SwAV loss
- 1.973
- Trustworthiness (k = 10)
- 0.9557
- Alignment (lower = views closer)
- 0.0742
- Uniformity (lower = more spread)
- −0.0381
- 5-NN probe accuracy (species)
- 95.3%
Plots
View data
| species | Component 1 | Component 2 |
|---|---|---|
| setosa | 1.885 | 0.3498 |
| setosa | 3.417 | −0.4963 |
| setosa | 3.436 | −0.3341 |
| setosa | 3.675 | −0.4491 |
| setosa | 1.894 | 0.4921 |
| setosa | −0.1290 | 1.308 |
| setosa | 2.997 | 0.0899 |
| setosa | 2.318 | 0.2103 |
| setosa | 4.548 | −0.6947 |
| setosa | 3.275 | −0.3957 |
| setosa | 0.6534 | 0.7638 |
| setosa | 2.624 | 0.1746 |
| setosa | 3.750 | −0.6007 |
| setosa | 4.904 | −0.8264 |
| setosa | −0.6393 | 1.381 |
| setosa | −1.676 | 2.184 |
| setosa | 0.1431 | 1.251 |
| setosa | 1.754 | 0.4424 |
| setosa | −0.4742 | 1.201 |
| setosa | 1.037 | 0.9511 |
| setosa | 1.199 | 0.3361 |
| setosa | 1.111 | 0.8891 |
| setosa | 3.100 | 0.3006 |
| setosa | 1.749 | 0.3788 |
| setosa | 2.389 | 0.2525 |
| setosa | 3.076 | −0.3969 |
| setosa | 1.974 | 0.4186 |
| setosa | 1.570 | 0.3942 |
| setosa | 1.906 | 0.2243 |
| setosa | 3.200 | −0.2441 |
| setosa | 3.229 | −0.3402 |
| setosa | 1.107 | 0.5197 |
| setosa | 0.4504 | 1.250 |
| setosa | −0.5159 | 1.555 |
| setosa | 3.125 | −0.3308 |
| setosa | 2.964 | −0.2262 |
| setosa | 1.023 | 0.4764 |
| setosa | 2.263 | 0.3775 |
| setosa | 4.413 | −0.6561 |
| setosa | 2.075 | 0.2294 |
| setosa | 2.071 | 0.3990 |
| setosa | 5.729 | −0.8965 |
| setosa | 3.986 | −0.4525 |
| setosa | 1.475 | 0.7598 |
| setosa | 0.6589 | 1.145 |
| setosa | 3.450 | −0.4588 |
| setosa | 1.100 | 0.8816 |
| setosa | 3.540 | −0.3436 |
| setosa | 0.8879 | 0.7380 |
| setosa | 2.604 | 0.0300 |
| versicolor | −2.724 | 0.4463 |
| versicolor | −2.141 | 0.6690 |
| versicolor | −2.362 | 0.1137 |
| versicolor | 1.030 | −0.3488 |
| versicolor | −1.600 | 0.1861 |
| versicolor | −0.8857 | 0.5887 |
| versicolor | −1.991 | 0.6937 |
| versicolor | 2.476 | −0.1314 |
| versicolor | −1.915 | 0.3116 |
| versicolor | 0.2682 | 0.3383 |
First 60 of 150 rows.
View data
| Part | Loss | Epoch |
|---|---|---|
| Swapped prediction | 4.724 | 1 |
| Swapped prediction | 4.902 | 2 |
| Swapped prediction | 4.594 | 3 |
| Swapped prediction | 4.418 | 4 |
| Swapped prediction | 4.153 | 5 |
| Swapped prediction | 4.282 | 6 |
| Swapped prediction | 3.815 | 7 |
| Swapped prediction | 3.654 | 8 |
| Swapped prediction | 3.799 | 9 |
| Swapped prediction | 3.502 | 10 |
| Swapped prediction | 3.330 | 11 |
| Swapped prediction | 3.318 | 12 |
| Swapped prediction | 3.114 | 13 |
| Swapped prediction | 3.115 | 14 |
| Swapped prediction | 2.930 | 15 |
| Swapped prediction | 3.042 | 16 |
| Swapped prediction | 2.637 | 17 |
| Swapped prediction | 2.635 | 18 |
| Swapped prediction | 2.460 | 19 |
| Swapped prediction | 2.444 | 20 |
| Swapped prediction | 2.546 | 21 |
| Swapped prediction | 2.094 | 22 |
| Swapped prediction | 2.301 | 23 |
| Swapped prediction | 1.942 | 24 |
| Swapped prediction | 2.144 | 25 |
| Swapped prediction | 2.073 | 26 |
| Swapped prediction | 2.130 | 27 |
| Swapped prediction | 2.111 | 28 |
| Swapped prediction | 1.949 | 29 |
| Swapped prediction | 1.990 | 30 |
| Swapped prediction | 2.019 | 31 |
| Swapped prediction | 2.109 | 32 |
| Swapped prediction | 1.920 | 33 |
| Swapped prediction | 1.990 | 34 |
| Swapped prediction | 1.955 | 35 |
| Swapped prediction | 1.882 | 36 |
| Swapped prediction | 1.940 | 37 |
| Swapped prediction | 2.005 | 38 |
| Swapped prediction | 1.924 | 39 |
| Swapped prediction | 1.973 | 40 |
Assumptions
- The representation uses several directions — The first principal direction holds 85% of the representation's variance.
- Neighbors share the label at least as often as in the raw data — 5-nearest-neighbor accuracy for species: 95.3% on the representation vs 94.7% on the standardized columns.
Rows per SwAV prototype
| Prototype | Rows |
|---|---|
| 1 | 2 |
| 2 | 0 |
| 3 | 48 |
| 4 | 99 |
| 5 | 1 |
| 6 | 0 |
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 e2faeb455feb1302
# 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_swav_full_batch/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
# %% swav 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 <- "swav"
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(40),
lr = 0.005,
batch_size = NULL,
weight_decay = 0,
seed = 42,
redundancy_weight = 0.005,
vicreg_weights = c(25, 25, 1),
prototypes = as.integer(6),
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_swav_full_batch/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(EMB)) emb[[paste0("dim_", j)]] <- E[, j]
emb$prototype <- as.integer(fit$assign) # each row's nearest SwAV prototype (1-based)
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$prototypes_used <- sum(fit$prototype_sizes > 0)
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,
tables = list(list(
key = "prototypes", title = "Rows per SwAV prototype",
columns = list(list(key = "prototype", label = "Prototype", type = "integer"), list(key = "rows", label = "Rows", type = "integer")),
rows = lapply(seq_along(fit$prototype_sizes), function(k) list(prototype = k, rows = as.integer(fit$prototype_sizes[k])))
)),
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 SwAV encoder on SCARF's corrupted views turned 150 rows (4 features) into 4-dimensional representations (final SwAV loss 1.973); neighborhoods are kept with trustworthiness 0.956. A 5-nearest-neighbor probe recovers species for 95.3% of rows (94.7% on the raw columns).
- Final SwAV loss
- 1.973
- Trustworthiness (k = 10)
- 0.9557
- Alignment (lower = views closer)
- 0.0742
- Uniformity (lower = more spread)
- −0.0381
- 5-NN probe accuracy (species)
- 95.3%
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- The representation uses several directions — The first principal direction holds 85% of the representation's variance.
- Neighbors share the label at least as often as in the raw data — 5-nearest-neighbor accuracy for species: 95.3% on the representation vs 94.7% on the standardized columns.
Rows per SwAV prototype
| Prototype | Rows |
|---|---|
| 1 | 2 |
| 2 | 0 |
| 3 | 48 |
| 4 | 99 |
| 5 | 1 |
| 6 | 0 |
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 e2faeb455feb1302
# 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_swav_full_batch/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))
# %% swav 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 = "swav"
TITLE = csssl.TITLES[OBJECTIVE]
fit = csssl.fit_ssl(
X, groups, HIDDEN, EMB, OBJECTIVE,
activation="relu",
corruption=0.6,
epochs=40,
lr=0.005,
batch_size=None,
weight_decay=0,
seed=42,
redundancy_weight=0.005,
vicreg_weights=(25, 25, 1),
prototypes=6,
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_swav_full_batch/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64), **{f"dim_{j + 1}": E[:, j] for j in range(EMB)}})
emb["prototype"] = fit["assign"].astype(np.int64) + 1 # each row's nearest SwAV prototype (1-based)
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["prototypes_used"] = int(np.sum(fit["prototype_sizes"] > 0))
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,
"tables": [{
"key": "prototypes",
"title": "Rows per SwAV prototype",
"columns": [{"key": "prototype", "label": "Prototype", "type": "integer"}, {"key": "rows", "label": "Rows", "type": "integer"}],
"rows": [{"prototype": k + 1, "rows": int(c)} for k, c in enumerate(fit["prototype_sizes"])],
}],
"artifacts": [
{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"},
{"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet"},
],
})
Check your understanding
CheckpointCheck yourself
What could a two-view objective with no negatives and no other guard learn?
Show the answer
Answer: a
Agreement between views is trivially perfect when everything maps to one point. Stop-gradients, decorrelation, variance hinges and balanced prototypes each rule that out.
Check yourself
What does SimSiam's stop-gradient do?
Show the answer
Answer: b
One branch predicts the other's projection through a small predictor; gradients flow only through the predicting branch. The paper found this alone prevents collapse.
Check yourself
How does BYOL's target network change during training?
Show the answer
Answer: b
The target is a moving average of the online encoder and head. Its momentum rises from the chosen value to 1 on a cosine schedule, and no gradient reaches it.
Check yourself
Barlow Twins ends with a loss of 1.8 and VICReg with 19. Which representation is better?
Show the answer
Answer: c
Each objective measures something different on its own scale. The checks every run reports are on one scale across objectives.
Try one
In the appIn Discover, open Contrastive representation (SCARF) under Map the data and change Objective. Each objective shows its own settings; the map, the probe and the collapse check stay the same.
Concepts in this lesson