Skip to content

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.

Advanced ~15 min10 steps

What runs in CodeSplash

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

Read first

01

Regularize the batch, not the pairs

Read

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

How sure?
0.20

Batch size

Each item's negatives are the rest of the batch.

Objective

Without labels, a batch can't tell them apart. Off: they're masked out.

0.30
300
0.80

Multiplied by min(τ, 0.15)², so low temperatures take smaller steps.

Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

02

Barlow Twins

Read

Barlow 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 CC. The loss wants CC to be the identity:

L=∑i(1−Cii)2+λ∑i≠jCij2.L = \sum_i (1 - C_{ii})^2 + \lambda \sum_{i \ne j} C_{ij}^2 .

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 λ\lambda the loss is 0.0050: the off-diagonal is high, but cheap at that weight.

03

Barlow Twins on penguins

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

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

Contrastive representation (principal components 1 and 2)Which rows group together, and how well separated are the groups?
View data
speciesComponent 1Component 2
Adelie−2.6670.6638
Adelie−2.590−0.4646
Adelie−2.359−0.3688
Adelie−1.452−0.1007
Adelie−2.8280.1523
Adelie−2.6161.229
Adelie−2.926−0.4506
Adelie−1.8711.512
Adelie−2.6550.1348
Adelie−2.2040.5448
Adelie−2.589−0.3359
Adelie−2.809−0.4170
Adelie−2.825−0.5589
Adelie−2.6131.531
Adelie−2.5092.058
Adelie−3.030−0.2977
Adelie−2.504−0.0343
Adelie−1.6031.597
Adelie−3.512−0.0996
Adelie−1.5521.595
Adelie−2.177−0.1310
Adelie−1.7200.6069
Adelie−1.323−0.2082
Adelie−1.0830.5147
Adelie−1.3480.5295
Adelie−1.404−0.1372
Adelie−1.4940.3430
Adelie−1.468−0.3947
Adelie−2.369−0.1052
Adelie−1.2700.3650
Adelie−2.552−0.6032
Adelie−2.1590.6569
Adelie−2.315−0.3980
Adelie−1.6760.3906
Adelie−1.816−0.1410
Adelie−1.0521.475
Adelie−1.5841.001
Adelie−2.182−0.5812
Adelie−2.844−0.0969
Adelie−0.95210.8477
Adelie−2.903−0.2148
Adelie−1.0850.4253
Adelie−2.798−0.0150
Adelie−0.20100.6722
Adelie−2.586−0.3675
Adelie−0.74890.9444
Adelie−2.3600.2019
Adelie−2.866−0.1937
Adelie−2.223−0.0333
Adelie−1.0471.170
Adelie−1.255−0.4222
Adelie−0.53300.4830
Adelie−1.350−0.2315
Adelie0.01660.2981
Adelie−1.955−0.0738
Adelie−0.82890.1475
Adelie−1.207−0.4279
Adelie−0.65310.1936
Adelie−2.001−0.1691
Adelie−0.83750.4265

First 60 of 344 rows.

Barlow Twins loss by epochIs the network still learning, and which part of its loss moves?
View data
PartLossEpoch
On-diagonal3.4871
On-diagonal3.2362
On-diagonal3.9673
On-diagonal2.6594
On-diagonal2.8735
On-diagonal2.5996
On-diagonal2.9087
On-diagonal2.6868
On-diagonal2.4749
On-diagonal2.34310
On-diagonal2.55011
On-diagonal2.44612
On-diagonal2.15713
On-diagonal2.14314
On-diagonal2.49315
On-diagonal1.97316
On-diagonal1.68917
On-diagonal1.76118
On-diagonal1.76319
On-diagonal1.87420
On-diagonal1.97921
On-diagonal1.55622
On-diagonal1.74523
On-diagonal1.62224
On-diagonal2.08125
On-diagonal1.26626
On-diagonal1.98627
On-diagonal1.44528
On-diagonal1.52329
On-diagonal1.46330
Off-diagonal (× λ)0.04701
Off-diagonal (× λ)0.06442
Off-diagonal (× λ)0.05403
Off-diagonal (× λ)0.09784
Off-diagonal (× λ)0.10405
Off-diagonal (× λ)0.12506
Off-diagonal (× λ)0.09637
Off-diagonal (× λ)0.12888
Off-diagonal (× λ)0.13349
Off-diagonal (× λ)0.159410
Off-diagonal (× λ)0.136911
Off-diagonal (× λ)0.159012
Off-diagonal (× λ)0.177513
Off-diagonal (× λ)0.187714
Off-diagonal (× λ)0.164815
Off-diagonal (× λ)0.213116
Off-diagonal (× λ)0.295917
Off-diagonal (× λ)0.290118
Off-diagonal (× λ)0.259619
Off-diagonal (× λ)0.244820
Off-diagonal (× λ)0.231121
Off-diagonal (× λ)0.320322
Off-diagonal (× λ)0.259023
Off-diagonal (× λ)0.301924
Off-diagonal (× λ)0.239625
Off-diagonal (× λ)0.396626
Off-diagonal (× λ)0.266927
Off-diagonal (× λ)0.353728
Off-diagonal (× λ)0.344129
Off-diagonal (× λ)0.372330
Cross-correlation of the two views (Barlow Twins)What do the values of a square or rectangular result matrix look like at a glance?

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 viewrRowCorrelation
z10.54z10.5351
z20.45z10.4508
z3-0.47z1−0.4696
z4-0.55z1−0.5505
z50.48z10.4819
z60.54z10.5354
z10.51z20.5140
z20.47z20.4665
z3-0.45z2−0.4488
z4-0.52z2−0.5204
z50.44z20.4419
z60.52z20.5208
z1-0.45z3−0.4518
z2-0.36z3−0.3611
z30.49z30.4909
z40.50z30.4964
z5-0.50z3−0.5009
z6-0.45z3−0.4477
z1-0.52z4−0.5250
z2-0.43z4−0.4318
z30.49z40.4894
z40.55z40.5524
z5-0.51z4−0.5065
z6-0.52z4−0.5228
z10.46z50.4620
z20.36z50.3583
z3-0.49z5−0.4926
z4-0.51z5−0.5096
z50.51z50.5138
z60.45z50.4548
z10.53z60.5349
z20.45z60.4547
z3-0.47z6−0.4672
z4-0.55z6−0.5489
z50.48z60.4769
z60.54z60.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")
  )
))
Python

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.

04

VICReg: three terms, three failures

Read

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

05

VICReg on Pima

Explore
Contrastive representation (SCARF)Recorded · Python and R agreeRecorded 2026-11-25 · 20 values compared · largest relative difference 5.5e-5
R

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

Contrastive representation (principal components 1 and 2)Which rows group together, and how well separated are the groups?
View data
GroupComponent 1Component 2
All rows−1.5970.5530
All rows−0.00380.6966
All rows0.6302−0.7124
All rows−0.7062−1.917
All rows−1.5761.132
All rows2.5310.0242
All rows−1.6830.5129
All rows−0.27840.3678
All rows3.6430.7543
All rows0.7746−1.871
All rows3.643−1.323
All rows−0.04770.3270
All rows0.51340.4486
All rows3.3201.006
All rows0.2628−1.504
All rows0.02721.465
All rows2.3741.190
All rows1.104−0.5184
All rows−0.37780.1996
All rows−1.1581.385
All rows0.89151.558
All rows1.3420.0735
All rows2.0051.077
All rows−0.30101.675
All rows−0.88060.0816
All rows0.1246−0.5521
All rows0.70561.561
All rows−0.7581−0.0886
All rows−1.223−0.7130
All rows−0.37290.2543
All rows−0.5049−0.4853
All rows−1.4470.3746
All rows−0.8827−0.0638
All rows−0.96520.5929
All rows−0.2871−0.7429
All rows2.8461.180
All rows0.50661.459
All rows0.14381.529
All rows2.4221.008
All rows−1.2050.3001
All rows1.036−0.5587
All rows1.9090.7541
All rows0.21100.8283
All rows−0.11851.614
All rows−0.74210.2332
All rows−1.1320.4431
All rows−1.783−0.3311
All rows4.9600.4781
All rows−1.7540.0779
All rows−0.6006−2.253
All rows−0.19661.179
All rows−0.83811.073
All rows−0.4826−0.1608
All rows−1.556−0.1042
All rows−1.5440.4449
All rows1.2800.5802
All rows−1.1920.4690
All rows0.08220.8861
All rows−1.4010.2451
All rows0.9145−1.853

First 60 of 532 rows.

VICReg loss by epochIs the network still learning, and which part of its loss moves?
View data
PartLossEpoch
Invariance8.6751
Invariance4.9812
Invariance3.9333
Invariance3.2524
Invariance3.7235
Invariance4.0996
Invariance4.6017
Invariance4.8708
Invariance5.4969
Invariance5.20510
Invariance5.12711
Invariance4.94312
Invariance4.60813
Invariance5.09714
Invariance6.22215
Invariance5.76316
Invariance5.66817
Invariance6.17718
Invariance5.95819
Invariance5.95420
Variance12.6781
Variance15.4832
Variance16.7403
Variance17.2964
Variance16.8815
Variance16.4306
Variance15.4677
Variance14.7978
Variance14.5689
Variance14.59910
Variance14.79111
Variance14.93312
Variance14.90413
Variance14.66514
Variance13.68715
Variance13.76116
Variance13.31317
Variance12.91718
Variance12.85219
Variance13.12820
Covariance0.58661
Covariance0.16132
Covariance0.06993
Covariance0.04564
Covariance0.05435
Covariance0.06976
Covariance0.10837
Covariance0.14188
Covariance0.16309
Covariance0.148410
Covariance0.132111
Covariance0.121812
Covariance0.119913
Covariance0.130214
Covariance0.182915
Covariance0.185116
Covariance0.212117
Covariance0.247118
Covariance0.263219
Covariance0.258720

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")
  )
))
Python

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.

06

SwAV: balanced prototypes

Read

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

07

SwAV on iris

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

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

Contrastive representation (principal components 1 and 2)Which rows group together, and how well separated are the groups?
View data
speciesComponent 1Component 2
setosa1.8850.3498
setosa3.417−0.4963
setosa3.436−0.3341
setosa3.675−0.4491
setosa1.8940.4921
setosa−0.12901.308
setosa2.9970.0899
setosa2.3180.2103
setosa4.548−0.6947
setosa3.275−0.3957
setosa0.65340.7638
setosa2.6240.1746
setosa3.750−0.6007
setosa4.904−0.8264
setosa−0.63931.381
setosa−1.6762.184
setosa0.14311.251
setosa1.7540.4424
setosa−0.47421.201
setosa1.0370.9511
setosa1.1990.3361
setosa1.1110.8891
setosa3.1000.3006
setosa1.7490.3788
setosa2.3890.2525
setosa3.076−0.3969
setosa1.9740.4186
setosa1.5700.3942
setosa1.9060.2243
setosa3.200−0.2441
setosa3.229−0.3402
setosa1.1070.5197
setosa0.45041.250
setosa−0.51591.555
setosa3.125−0.3308
setosa2.964−0.2262
setosa1.0230.4764
setosa2.2630.3775
setosa4.413−0.6561
setosa2.0750.2294
setosa2.0710.3990
setosa5.729−0.8965
setosa3.986−0.4525
setosa1.4750.7598
setosa0.65891.145
setosa3.450−0.4588
setosa1.1000.8816
setosa3.540−0.3436
setosa0.88790.7380
setosa2.6040.0300
versicolor−2.7240.4463
versicolor−2.1410.6690
versicolor−2.3620.1137
versicolor1.030−0.3488
versicolor−1.6000.1861
versicolor−0.88570.5887
versicolor−1.9910.6937
versicolor2.476−0.1314
versicolor−1.9150.3116
versicolor0.26820.3383

First 60 of 150 rows.

SwAV loss by epochIs the network still learning, and which part of its loss moves?
View data
PartLossEpoch
Swapped prediction4.7241
Swapped prediction4.9022
Swapped prediction4.5943
Swapped prediction4.4184
Swapped prediction4.1535
Swapped prediction4.2826
Swapped prediction3.8157
Swapped prediction3.6548
Swapped prediction3.7999
Swapped prediction3.50210
Swapped prediction3.33011
Swapped prediction3.31812
Swapped prediction3.11413
Swapped prediction3.11514
Swapped prediction2.93015
Swapped prediction3.04216
Swapped prediction2.63717
Swapped prediction2.63518
Swapped prediction2.46019
Swapped prediction2.44420
Swapped prediction2.54621
Swapped prediction2.09422
Swapped prediction2.30123
Swapped prediction1.94224
Swapped prediction2.14425
Swapped prediction2.07326
Swapped prediction2.13027
Swapped prediction2.11128
Swapped prediction1.94929
Swapped prediction1.99030
Swapped prediction2.01931
Swapped prediction2.10932
Swapped prediction1.92033
Swapped prediction1.99034
Swapped prediction1.95535
Swapped prediction1.88236
Swapped prediction1.94037
Swapped prediction2.00538
Swapped prediction1.92439
Swapped prediction1.97340

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

PrototypeRows
12
20
348
499
51
60
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")
  )
))
Python

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

PrototypeRows
12
20
348
499
51
60
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.

08

What runs here

Read
09

Check: batch-statistics objectives

Checkpoint

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

10

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