Skip to content

Representations without negatives: SimSiam, BYOL, Barlow Twins, VICReg and SwAV

The contrastive encoder can swap InfoNCE for five objectives that never compare a row with other rows. What each one does to avoid collapse, which numbers show it worked, and why a label probe still decides.

Advanced ~10 min10 steps

What runs in CodeSplash

You will be able to

  • Say why a two-view objective without negatives risks collapse, and how each of the five avoids it
  • Read Barlow Twins' cross-correlation and VICReg's loss parts
  • Compare objectives with the label probe and top_pc_share, not their loss values

Read first

01

Two views, no negatives

Read

The contrastive encoder pairs each row with a corrupted copy and, with InfoNCE, asks it to pick its own copy out of the batch. The other rows are the negatives. Without them, an encoder could map every row to one point: both views would agree perfectly. That is collapse.

The Objective option offers five ways to learn from two views without negatives, each with its own guard against collapse (self-supervised learning without negativesSelf-supervised learning without negativesObjectives that learn from two views of each row without contrasting it against other rows, and avoid collapse by other means.).

ObjectiveWhat stops collapse
SimSiamA predictor on one side and no gradient on the other
BYOLA predictor and a slow target copy
Barlow TwinsCoordinates must not repeat each other
VICRegEach coordinate must keep a spread across the batch
SwAVRows must spread evenly over learned prototypes
02

BYOL: a slowly moving target

Read

BYOLBYOLAn online network predicts a momentum target network's representation of another view; there are no negative rows. predicts, from one view, what a target copy of the encoder makes of the other view. The target gets no gradient: after every step it moves a small share of the way toward the trained encoder, set by Target momentum. On the penguins with the default 0.996, the probe recovers the species for 98.5% of rows.

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

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

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

Plots

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

First 60 of 344 rows.

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

Assumptions

  • The representation uses several directions — The first principal direction holds 51% of the representation's variance.
  • Neighbors share the label at least as often as in the raw data — 5-nearest-neighbor accuracy for species: 98.5% on the representation vs 98.8% on the standardized columns.
The exact R script · R R version 4.5.1 (2025-06-13)
# Contrastive representation (SCARF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.contrastive 1.3.0 · spec 8a7a49a6ec29106f
# Dataset: ml_penguins (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)  # cs_deep_fit_scarf: SCARF contrastive encoder (twin of codesplash.deep.generative)

# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE <- "median"
SCALE <- "standard"
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/discover.contrastive/penguins_byol/out-r")
FEATURES <- c("island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    island = "categorical",
    bill_len = "numeric",
    bill_dep = "numeric",
    flipper_len = "numeric",
    body_mass = "numeric",
    sex = "categorical"
  ),
  levels = list(
    island = c("Biscoe", "Dream", "Torgersen"),
    sex = c("female", "male")
  ),
  impute = IMPUTE,
  scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df))  # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
LABEL <- "species"
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.parquet", col_select = LABEL))[[LABEL]]
groups <- cs_deep_feature_groups(fitted)  # design columns of each feature: corruption swaps whole features
if (length(rows) < 3L) cs_error("CS_E_TOO_FEW_ROWS", what = "Contrastive representation", min = 3L, n = length(rows))  # map, trustworthiness, probe

# %% byol on SCARF's views (torch for R, float64, one thread): the row and its corrupted copy, a loss without negatives
HIDDEN <- as.integer(unlist(c(32)))
EMB <- as.integer(6)
OBJECTIVE <- "byol"
TITLE <- cs_ssl_title(OBJECTIVE)
fit <- cs_deep_fit_ssl(  # twin of codesplash.deep.ssl.fit_ssl (objectives without negatives)
  X, groups, HIDDEN, EMB, OBJECTIVE,
  activation = "relu",
  corruption = 0.6,
  epochs = as.integer(30),
  lr = 0.001,
  batch_size = 64,
  weight_decay = 0,
  seed = 42,
  redundancy_weight = 0.005,
  vicreg_weights = c(25, 25, 1),
  prototypes = as.integer(16),
  swav_temperature = 0.1,
  swav_epsilon = 0.05,
  target_momentum = 0.996,  # tau_base: the target follows the online network after every step
  sinkhorn_iterations = as.integer(3)
)
E <- fit$embedding  # encoder output (the representation), n x EMB
P2 <- cs_deep_pca2(E)  # its first two principal components, for the map

# %% How good is the representation? Neighborhoods, alignment / uniformity, and a label probe
sample <- cs_ml_sample_rows(length(rows))
k_eval <- min(10L, length(sample) - 2L)
trust <- cs_ml_trustworthiness(X[sample, , drop = FALSE], E[sample, , drop = FALSE], k_eval)
unif <- cs_deep_uniformity(fit$projection[sample, , drop = FALSE])
labels <- NULL
if (!is.null(LABEL)) labels <- as.character(df[[LABEL]][rows[sample] + 1L])
probe <- if (!is.null(labels)) cs_deep_knn_probe(E[sample, , drop = FALSE], labels) else NaN
probe_raw <- if (!is.null(labels)) cs_deep_knn_probe(X[sample, , drop = FALSE], labels) else NaN
Ec <- sweep(E, 2, colMeans(E))
ev <- if (EMB > 1L) sort(eigen(crossprod(Ec) / nrow(E), symmetric = TRUE, only.values = TRUE)$values, decreasing = TRUE) else mean(Ec[, 1]^2)
top_share <- if (sum(ev) > 0) ev[1] / sum(ev) else 1

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.contrastive/penguins_byol/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(EMB)) emb[[paste0("dim_", j)]] <- E[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
hist <- data.frame(epoch = vapply(fit$history, function(h) as.numeric(h$epoch), numeric(1)),
                   loss = vapply(fit$history, function(h) h$loss, numeric(1)))
for (pt in fit$parts) hist[[pt[1]]] <- vapply(fit$history, function(h) h[[pt[1]]], numeric(1))
nanoparquet::write_parquet(hist, file.path(out, "history.parquet"))

# %% Result
values <- list(
  n = length(rows), n_features = length(groups), embedding_dim = EMB, final_loss = hist$loss[nrow(hist)],
  epochs_run = fit$epochs_run, trustworthiness = trust, alignment = fit$alignment, uniformity = unif,
  top_pc_share = top_share, probe_acc = probe, probe_acc_raw = probe_raw
)
for (j in seq_len(EMB)) values[[sprintf("emb_check[%d]", j)]] <- cs_ml_checksum(E[, j], rows)
values$target_gap <- fit$target_gap  # mean squared distance between the online and target unit projections
pick <- cs_ml_sample_rows(length(rows), 5000)
grp <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
  g <- df[[LABEL]][rows[pick] + 1L]
  ifelse(is.na(g), "(missing)", as.character(g))
}
charts <- list(cs_chart("map", "cluster-scatter", "Contrastive representation (principal components 1 and 2)", list(
  x = cs_col("Component 1", P2[pick, 1], "numeric"),
  y = cs_col("Component 2", P2[pick, 2], "numeric"),
  cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, grp, "categorical")
), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ","))))
part_keys <- vapply(fit$parts, function(pt) pt[1], character(1))
part_labels <- vapply(fit$parts, function(pt) pt[2], character(1))
charts[[2]] <- cs_chart("training", "training-components", paste(TITLE, "loss by epoch"), list(
  x = cs_col("Epoch", rep(hist$epoch, length(part_keys)), "numeric"),
  value = cs_col("Loss", unlist(lapply(part_keys, function(k) hist[[k]])), "numeric"),
  component = cs_col("Part", rep(part_labels, each = nrow(hist)), "categorical", levels = part_labels)
))
collapsed <- EMB > 1L && top_share > 0.9
assumptions <- list(list(
  key = "collapse", label = "The representation uses several directions",
  status = if (collapsed) "warn" else "pass",
  detail = paste0(sprintf("The first principal direction holds %.0f%% of the representation's variance", 100 * top_share),
                  if (collapsed) " — nearly everything lies on one line (dimensional collapse)." else ".")
))
if (!is.null(LABEL) && !is.nan(probe) && !is.nan(probe_raw)) {
  assumptions[[2]] <- list(
    key = "probe", label = "Neighbors share the label at least as often as in the raw data",
    status = if (probe < probe_raw - 0.05) "warn" else "pass",
    detail = sprintf("5-nearest-neighbor accuracy for %s: %.1f%% on the representation vs %.1f%% on the standardized columns.", LABEL, 100 * probe, 100 * probe_raw)
  )
}
summary <- sprintf("A %s encoder on SCARF's corrupted views turned %d rows (%d features) into %d-dimensional representations (final %s loss %.3f); neighborhoods are kept with trustworthiness %.3f.",
                   TITLE, length(rows), length(groups), EMB, TITLE, values$final_loss, trust)
if (!is.null(LABEL) && !is.nan(probe)) summary <- paste0(summary, sprintf(" A 5-nearest-neighbor probe recovers %s for %.1f%% of rows (%.1f%% on the raw columns).", LABEL, 100 * probe, 100 * probe_raw))
statistics <- list(
  list(key = "final_loss", label = paste("Final", TITLE, "loss"), value = values$final_loss),
  list(key = "trustworthiness", label = sprintf("Trustworthiness (k = %d)", k_eval), value = trust),
  list(key = "alignment", label = "Alignment (lower = views closer)", value = values$alignment),
  list(key = "uniformity", label = "Uniformity (lower = more spread)", value = unif)
)
if (!is.null(LABEL)) statistics[[5]] <- list(key = "probe_acc", label = sprintf("5-NN probe accuracy (%s)", LABEL), value = probe, format = "percent")
statistics <- append(statistics, list(list(key = "target_gap", label = "Online–target gap (lower = target caught up)", value = values$target_gap)), after = 4L)
cs_publish(list(
  title = "Contrastive representation (SCARF)",
  engine = cs_engine_info("torch", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = statistics,
  charts = charts,
  assumptions = assumptions,
  values = values,
  warnings = warnings,
  artifacts = list(
    list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"),
    list(key = "history", path = file.path(out, "history.parquet"), format = "parquet")
  )
))
Python

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

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

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • The representation uses several directions — The first principal direction holds 51% of the representation's variance.
  • Neighbors share the label at least as often as in the raw data — 5-nearest-neighbor accuracy for species: 98.5% on the representation vs 98.8% on the standardized columns.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Contrastive representation (SCARF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.contrastive 1.3.0 · spec 8a7a49a6ec29106f
# Dataset: ml_penguins (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.deep import generative as gen  # twin of codesplashr::cs_deep_fit_scarf (shared weights and corruption draws)
from codesplash.deep import ssl as csssl  # twin of codesplashr::cs_deep_fit_ssl (objectives without negatives)
from codesplash.ml import embed as csembed

# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE = "median"
SCALE = "standard"
from codesplash.deep import trainer as deep_trainer  # training options, live progress, checkpoints (twin: cs_deep_trainer_*)

deep_trainer.configure(
    {
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/discover.contrastive/penguins_byol/out-python",
)
FEATURES = ["island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"]
df = pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "island": "categorical",
        "bill_len": "numeric",
        "bill_dep": "numeric",
        "flipper_len": "numeric",
        "body_mass": "numeric",
        "sex": "categorical",
    },
    levels={
        "island": ["Biscoe", "Dream", "Torgersen"],
        "sex": ["female", "male"],
    },
    impute=IMPUTE,
    scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df)  # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
LABEL = "species"
if LABEL:
    df[LABEL] = pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=[LABEL])[LABEL]
groups = gen.feature_groups(fitted)  # design columns of each feature: corruption swaps whole features
if len(rows) < 3:  # the map, trustworthiness (k = n − 2) and the probe need three rows
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="Contrastive representation", min=3, n=len(rows))

# %% byol on SCARF's views (PyTorch, float64, one thread): the row and its corrupted copy, a loss without negatives
HIDDEN = [int(u) for u in [32]]
EMB = 6
OBJECTIVE = "byol"
TITLE = csssl.TITLES[OBJECTIVE]
fit = csssl.fit_ssl(
    X, groups, HIDDEN, EMB, OBJECTIVE,
    activation="relu",
    corruption=0.6,
    epochs=30,
    lr=0.001,
    batch_size=64,
    weight_decay=0,
    seed=42,
    redundancy_weight=0.005,
    vicreg_weights=(25, 25, 1),
    prototypes=16,
    swav_temperature=0.1,
    swav_epsilon=0.05,
    sinkhorn_iterations=3,
    target_momentum=0.996,  # τ_base: the target follows the online network after every step
)
E = fit["embedding"]  # encoder output (the representation), n × EMB
P2 = gen.pca2(E)  # its first two principal components, for the map

# %% How good is the representation? Neighborhoods, alignment / uniformity, and a label probe
sample = csembed.sample_rows(len(rows))
k_eval = min(10, len(sample) - 2)
trust = csembed.trustworthiness(X[sample], E[sample], k_eval)
unif = gen.uniformity(fit["projection"][sample])
labels = None
if LABEL:
    labels = [None if pd.isna(v) else str(v) for v in df[LABEL].iloc[rows[sample]]]
probe = gen.knn_probe(E[sample], labels) if labels else float("nan")
probe_raw = gen.knn_probe(X[sample], labels) if labels else float("nan")
Ec = E - E.mean(axis=0)
ev = np.sort(np.linalg.eigvalsh(Ec.T @ Ec / len(E)))[::-1] if EMB > 1 else np.array([float(np.mean(Ec[:, 0] ** 2))])
top_share = float(ev[0] / ev.sum()) if ev.sum() > 0 else 1.0

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.contrastive/penguins_byol/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64), **{f"dim_{j + 1}": E[:, j] for j in range(EMB)}})
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
history = pd.DataFrame({"epoch": [h["epoch"] for h in fit["history"]], "loss": [h["loss"] for h in fit["history"]]})
for key, _ in fit["parts"]:
    history[key] = [h[key] for h in fit["history"]]
history.to_parquet(os.path.join(out, "history.parquet"), index=False)

# %% Result
values = {
    "n": len(rows),
    "n_features": len(groups),
    "embedding_dim": EMB,
    "final_loss": float(fit["history"][-1]["loss"]),
    "epochs_run": int(fit["epochs_run"]),
    "trustworthiness": trust,
    "alignment": float(fit["alignment"]),
    "uniformity": unif,
    "top_pc_share": top_share,
    "probe_acc": probe,
    "probe_acc_raw": probe_raw,
}
for j in range(EMB):
    values[f"emb_check[{j + 1}]"] = csembed.checksum(E[:, j], rows)
values["target_gap"] = float(fit["target_gap"])  # mean squared distance between the online and target unit projections
pick = csembed.sample_rows(len(rows), 5000)
grp = [("All rows" if LABEL is None else ("(missing)" if pd.isna(v) else str(v))) for v in (df[LABEL].iloc[rows[pick]] if LABEL else [None] * len(pick))]
charts = [cs.chart("map", "cluster-scatter", "Contrastive representation (principal components 1 and 2)", {
    "x": cs.col("Component 1", P2[pick, 0], "numeric"),
    "y": cs.col("Component 2", P2[pick, 1], "numeric"),
    "cluster": cs.col(LABEL or "Group", grp, "categorical"),
}, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown.")]
ep = [h["epoch"] for h in fit["history"]]
part_labels = [lab for _, lab in fit["parts"]]
charts.append(cs.chart("training", "training-components", f"{TITLE} loss by epoch", {
    "x": cs.col("Epoch", ep * len(part_labels), "numeric"),
    "value": cs.col("Loss", [h[key] for key, _ in fit["parts"] for h in fit["history"]], "numeric"),
    "component": cs.col("Part", [lab for lab in part_labels for _ in ep], "categorical", levels=part_labels),
}))
assumptions = [{
    "key": "collapse",
    "label": "The representation uses several directions",
    "status": "warn" if (EMB > 1 and top_share > 0.9) else "pass",
    "detail": f"The first principal direction holds {top_share:.0%} of the representation's variance"
              + (" — nearly everything lies on one line (dimensional collapse)." if EMB > 1 and top_share > 0.9 else "."),
}]
if LABEL and probe == probe and probe_raw == probe_raw:
    assumptions.append({
        "key": "probe",
        "label": "Neighbors share the label at least as often as in the raw data",
        "status": "warn" if probe < probe_raw - 0.05 else "pass",
        "detail": f"5-nearest-neighbor accuracy for {LABEL}: {probe:.1%} on the representation vs {probe_raw:.1%} on the standardized columns.",
    })
summary = (
    f"A {TITLE} encoder on SCARF's corrupted views turned {len(rows)} rows ({len(groups)} features) into {EMB}-dimensional "
    f"representations (final {TITLE} loss {values['final_loss']:.3f}); neighborhoods are kept with trustworthiness {trust:.3f}."
)
if LABEL and probe == probe:
    summary += f" A 5-nearest-neighbor probe recovers {LABEL} for {probe:.1%} of rows ({probe_raw:.1%} on the raw columns)."
cs.publish({
    "title": "Contrastive representation (SCARF)",
    "engine": cs.engine_info("torch", "numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "final_loss", "label": f"Final {TITLE} loss", "value": values["final_loss"]},
        {"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": trust},
        {"key": "alignment", "label": "Alignment (lower = views closer)", "value": values["alignment"]},
        {"key": "uniformity", "label": "Uniformity (lower = more spread)", "value": unif},
        {"key": "target_gap", "label": "Online–target gap (lower = target caught up)", "value": values["target_gap"]},
    ] +([{"key": "probe_acc", "label": f"5-NN probe accuracy ({LABEL})", "value": probe, "format": "percent"}] if LABEL else []),
    "charts": charts,
    "assumptions": assumptions,
    "values": values,
    "warnings": warnings,
    "artifacts": [
        {"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"},
        {"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet"},
    ],
})
03

Has the target caught up?

Predict

Predict first

That run takes 180 steps. Where does the online–target gap end, on its scale from 0 to 4?

Near 0: the target caught upWell above 0: the target still trails
Reveal

Well above 0: 1.75. At 0.996 the target moves 0.4% of the way per step, which suits runs of many thousands of steps. The online–target gapOnline–target gapMean squared distance between the online and target networks' unit-length projections of each row; 0 to 4, lower means caught up. measures lag, not quality; for short runs, try a target momentum of 0.99 or lower.

04

Barlow Twins: the cross-correlation

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 projection coordinate over the batch and correlates the row's view with the corrupted view. It wants 1 on the diagonal and 0 elsewhere.

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"},
    ],
})
05

How close to the identity?

Predict

Predict first

After 30 epochs on the penguins, where is the mean of the diagonal of the cross-correlation over all rows?

Close to 1About halfwayClose to 0
Reveal

About halfway: 0.516, with off-diagonal cells at 0.483 (root mean square). The corrupted view replaces a share of each row's features, so it can't match perfectly. Still, the 5-nearest-neighbor probe recovers the species for 98.3% of rows.

06

VICReg: three parts of one loss

Read

VICRegVICRegThree terms: views stay close (invariance), each coordinate keeps a spread near 1 (variance), coordinates stay uncorrelated (covariance). adds an invariance term (views close), a variance term (each coordinate's spread near 1) and a covariance term (coordinates uncorrelated). The VICReg loss by epoch chart draws the three loss partsLoss partsThe pieces a self-supervised loss adds up, each as the last epoch's mean: Barlow's on- and off-diagonal, VICReg's three terms..

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"},
    ],
})
07

Which part is largest?

Predict

Predict first

On the Pima rows after 20 epochs, which part is largest?

InvarianceVarianceCovariance
Reveal

Variance, at 13.1 of 19.3: many coordinates still spread less than 1 across the batch. Invariance is 5.95 and covariance 0.259. More epochs would push the variance term down.

08

Comparing objectives

Read

Losses of different objectives aren't on one scale, so compare the checks every run reports. On iris, the SimSiam encoder's probe recovers the species for 80.7% of rows, below the raw columns' 94.7%, and its first principal direction holds 83.7% of the variance. SwAVSwAVRows are assigned to learned prototypes in balanced groups, and each view must predict the group the other view was given. reaches 95.3% and keeps 4 prototypes in use. Each row's prototype is saved with its representation.

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"},
    ],
})
09

Check your understanding

Checkpoint

Check yourself

What could a two-view objective with no negatives and no other guard learn?

Show the answer

Answer: a

Agreement between views is trivially perfect when everything maps to one point. Stop-gradients, decorrelation, variance hinges and balanced prototypes each rule that out.

Check yourself

What does SimSiam's stop-gradient do?

Show the answer

Answer: b

One branch predicts the other's projection through a small predictor; gradients flow only through the predicting branch. The paper found this alone prevents collapse.

Check yourself

How does BYOL's target network change during training?

Show the answer

Answer: b

The target is a moving average of the online encoder and head. Its momentum rises from the chosen value to 1 on a cosine schedule, and no gradient reaches it.

Check yourself

Barlow Twins ends with a loss of 1.8 and VICReg with 19. Which representation is better?

Show the answer

Answer: c

Each objective measures something different on its own scale. The checks every run reports are on one scale across objectives.

10

Try one

In the app

In Discover, open Contrastive representation (SCARF) under Map the data and change Objective. Each objective shows its own settings; the map, the probe and the collapse check stay the same.

Concepts in this lesson