Barlow Twins, VICReg and SwAV: spread out, decorrelate, balance
Three more negative-free objectives: Barlow Twins pushes a cross-correlation toward the identity, VICReg adds variance and covariance terms, SwAV balances rows across prototypes. All run in CodeSplash.
What runs in CodeSplash
- DNN070Swapping Assignments between Views (SwAV) Runs in CodeSplash (Experimental)
- DNN072Barlow Twins Runs in CodeSplash (Experimental)
- DNN073Variance-Invariance-Covariance Regularization (VICReg) Runs in CodeSplash (Experimental)
- Contrastive representation (SCARF) Experimental
You will be able to
- Compute a Barlow Twins loss from a cross-correlation matrix
- Name VICReg's three terms and the failure each one prevents
- Explain SwAV's balanced prototype assignments and swapped prediction
- Read each objective's diagnostics in a CodeSplash run
Regularize the batch, not the pairs
ReadThe teacher–student methods avoided collapse with asymmetry. This family uses statistics of the whole batch instead: if every coordinate must vary across rows, and different coordinates must carry different information, a constant or one-line representation is ruled out by the loss itself.
All three run as Objective choices in Discover's Contrastive representation, with the same encoder and SCARF views as InfoNCE, so you can swap one for another on the same table.
Compare training with negatives and without them.
DExplorable · InfoNCE: temperature, negatives, collapse
How does contrastive learning learn useful embeddings without labels, and what keeps it from collapsing?
After training with this objective, where do the embeddings end up?
Batch size
Each item's negatives are the rest of the batch.
Objective
Without labels, a batch can't tell them apart. Off: they're masked out.
Multiplied by min(τ, 0.15)², so low temperatures take smaller steps.
Commit your prediction above to see the result
Make your prediction to see the result.
Barlow Twins
ReadBarlow TwinsBarlow TwinsPushes the two views' cross-correlation matrix toward the identity, so matching coordinates agree and different ones carry new information. standardizes each coordinate of the two views' embeddings across the batch and computes their cross-correlation matrix . The loss wants to be the identity:
The diagonal says matching coordinates agree across views; the off-diagonal says different coordinates don't repeat each other. In the reference's example the diagonal is 0.991, the off-diagonal 0.696, and with a small weight the loss is 0.0050: the off-diagonal is high, but cheap at that weight.
Barlow Twins on penguins
ExploreA 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"},
],
})
Open the cross-correlation heatmap. The mean diagonal is 0.516 and the root-mean-square off-diagonal 0.483: after a short run the coordinates still overlap a lot. The probe reaches 98.3% against 98.8% on raw columns.
Redundancy weight (λ) trades the two terms. Raise it and coordinates are pushed harder apart.
VICReg: three terms, three failures
ReadVICRegVICRegThree terms: views stay close (invariance), each coordinate keeps a spread near 1 (variance), coordinates stay uncorrelated (covariance). writes the three requirements as separate terms:
- invariance: mean squared distance between a row's two views;
- variance: a hinge that keeps each coordinate's SD across the batch above 1, so nothing shrinks to a constant;
- covariance: the sum of squared off-diagonal covariances, so coordinates don't repeat each other.
The paper weights them 25, 25 and 1. In the reference's example the invariance term is 0.01, the variance term 0.0 (every SD is above 1) and the covariance term 2.0, for a total of 2.25.
VICReg on Pima
ExploreA 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"},
],
})
Open Loss parts by epoch to see which of the three terms dominates and which is still falling. The total ends at 19.34; totals aren't comparable across objectives, only within a run. The first principal component holds 45.6% of the variance, so the variance and covariance terms kept the representation spread over several directions.
SwAV: balanced prototypes
ReadSwAVSwAVRows are assigned to learned prototypes in balanced groups, and each view must predict the group the other view was given. learns a set of prototype vectors. Each view's embedding is scored against them, and a few Sinkhorn steps turn the scores into balanced soft assignments: across the batch, every prototype gets an equal share of rows. Then each view must predict the other view's assignment, the swapped prediction.
Balance is the anti-collapse device: assigning every row to one prototype is not allowed. In the reference's example the swapped cross-entropy for one pair of views is 0.593.
SwAV on iris
ExploreA 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"},
],
})
With six prototypes, 4 end up as some row's nearest prototype. Each row's nearest prototype is saved with the representation. They are training devices, not discovered clusters: their number is a setting. The probe reaches 95.3% against 94.7% on raw columns.
What runs here
ReadCheck: batch-statistics objectives
CheckpointCheck yourself
What does Barlow Twins push the two views' cross-correlation matrix toward?
Show the answer
Answer: a
Ones on the diagonal make matching coordinates agree across views; zeros elsewhere stop coordinates from repeating each other.
Check yourself
After a Barlow Twins run the off-diagonal cross-correlations are still large. Which setting pushes them down harder?
Show the answer
Answer: b
λ weights the off-diagonal term. Raising it trades some diagonal agreement for less redundancy.
Check yourself
Which VICReg term stops every coordinate from shrinking to a constant?
Show the answer
Answer: b
Invariance alone would be minimized by a constant. The variance hinge rules that out; the covariance term stops coordinates from duplicating each other.
Check yourself
A VICReg run ends with a loss of 19 and an InfoNCE run with 3.9 on the same table. Which representation is better?
Show the answer
Answer: b
Losses are only comparable within one objective. Compare representations by what you use them for.
Check yourself
What stops SwAV from assigning every row to one prototype?
Show the answer
Answer: a
Balanced assignments forbid the trivial solution in which all rows share one prototype.
Check yourself
A SwAV run used 4 of its 6 prototypes. Has it found 4 clusters in the data?
Show the answer
Answer: b
Prototype use reflects the objective and settings. To claim clusters, run a clustering method and validate it.
Recap
Recap- Batch-statistics objectives rule out collapse in the loss itself.
- Barlow Twins pushes the cross-correlation toward the identity; VICReg separates invariance, variance and covariance.
- SwAV balances rows across prototypes and predicts one view's assignment from the other.
- Compare objectives by probes and collapse checks, never by their loss values.
Concepts in this lesson