CDiscover · discover.contrastive
Contrastive representation (SCARF)
Can a network learn row representations without labels, by telling each row apart from corrupted copies of the others?
Self-supervised representation learning for tables (SCARF). Each row gets a corrupted view in which a random share of its features takes the values of other rows; an encoder and a small projection head learn to match every row with its own view rather than with the other rows' views (InfoNCE loss). The encoder's output is a representation you can map, cluster or feed to a model. A label, when given, is used only to color the map and to probe how well neighbors share it. Lab tier: torch in both engines from the same initial weights and the same corruption draws.
A real result
Example “Penguins probe”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
A SCARF contrastive encoder turned 344 rows (6 features) into 8-dimensional representations (final InfoNCE loss 3.901); 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 InfoNCE loss
- 3.901
- Trustworthiness (k = 10)
- 0.9807
- Alignment (lower = views closer)
- 1.049
- Uniformity (lower = more spread)
- −1.514
- 5-NN probe accuracy (species)
- 98.3%
Plots
View data
| species | Component 1 | Component 2 |
|---|---|---|
| Adelie | 2.774 | −1.047 |
| Adelie | 1.915 | 0.9130 |
| Adelie | 1.737 | 0.7030 |
| Adelie | 1.223 | −0.5208 |
| Adelie | 2.398 | 0.7307 |
| Adelie | 2.956 | −1.940 |
| Adelie | 2.208 | 0.9186 |
| Adelie | 2.202 | −2.159 |
| Adelie | 2.042 | −0.1045 |
| Adelie | 2.501 | −1.059 |
| Adelie | 1.786 | 0.0384 |
| Adelie | 2.070 | 0.2609 |
| Adelie | 2.020 | 0.7916 |
| Adelie | 3.030 | −2.232 |
| Adelie | 2.725 | −2.541 |
| Adelie | 2.269 | 1.018 |
| Adelie | 2.099 | 0.6687 |
| Adelie | 2.068 | −2.496 |
| Adelie | 2.651 | 0.9900 |
| Adelie | 2.310 | −2.618 |
| Adelie | 1.740 | 1.707 |
| Adelie | 2.039 | −0.2494 |
| Adelie | 1.250 | 1.983 |
| Adelie | 1.506 | −0.2852 |
| Adelie | 1.601 | −0.1191 |
| Adelie | 1.231 | 1.961 |
| Adelie | 1.825 | −0.2493 |
| Adelie | 1.107 | 1.849 |
| Adelie | 1.894 | 1.726 |
| Adelie | 1.734 | −0.3572 |
| Adelie | 1.568 | 1.551 |
| Adelie | 2.251 | −0.3916 |
| Adelie | 1.624 | 1.375 |
| Adelie | 1.983 | −0.6697 |
| Adelie | 0.9698 | 1.364 |
| Adelie | 1.553 | −2.436 |
| Adelie | 2.011 | −1.594 |
| Adelie | 1.716 | 1.386 |
| Adelie | 2.267 | 1.418 |
| Adelie | 1.615 | −1.332 |
| Adelie | 2.042 | 1.448 |
| Adelie | 1.462 | −0.9915 |
| Adelie | 2.026 | 1.413 |
| Adelie | 0.8182 | −1.880 |
| Adelie | 1.573 | 1.424 |
| Adelie | 1.345 | −1.448 |
| Adelie | 2.450 | −0.3963 |
| Adelie | 2.277 | 0.4321 |
| Adelie | 1.476 | 1.368 |
| Adelie | 1.655 | −2.335 |
| Adelie | 0.9192 | 1.819 |
| Adelie | 1.112 | −0.8849 |
| Adelie | 0.9390 | 1.951 |
| Adelie | 0.5064 | −1.033 |
| Adelie | 1.408 | 1.915 |
| Adelie | 1.230 | −0.4059 |
| Adelie | 0.8233 | 1.800 |
| Adelie | 1.120 | −0.5507 |
| Adelie | 1.085 | 1.582 |
| Adelie | 1.310 | −0.5862 |
First 60 of 344 rows.
View data
| Part | Loss | Epoch |
|---|---|---|
| InfoNCE | 4.024 | 1 |
| InfoNCE | 4.025 | 2 |
| InfoNCE | 4.036 | 3 |
| InfoNCE | 3.985 | 4 |
| InfoNCE | 4.015 | 5 |
| InfoNCE | 3.964 | 6 |
| InfoNCE | 3.979 | 7 |
| InfoNCE | 3.981 | 8 |
| InfoNCE | 3.952 | 9 |
| InfoNCE | 3.956 | 10 |
| InfoNCE | 3.983 | 11 |
| InfoNCE | 3.921 | 12 |
| InfoNCE | 3.946 | 13 |
| InfoNCE | 3.941 | 14 |
| InfoNCE | 3.962 | 15 |
| InfoNCE | 3.968 | 16 |
| InfoNCE | 3.921 | 17 |
| InfoNCE | 3.936 | 18 |
| InfoNCE | 3.923 | 19 |
| InfoNCE | 3.938 | 20 |
| InfoNCE | 3.930 | 21 |
| InfoNCE | 3.928 | 22 |
| InfoNCE | 3.936 | 23 |
| InfoNCE | 3.907 | 24 |
| InfoNCE | 3.954 | 25 |
| InfoNCE | 3.877 | 26 |
| InfoNCE | 3.935 | 27 |
| InfoNCE | 3.921 | 28 |
| InfoNCE | 3.901 | 29 |
| InfoNCE | 3.910 | 30 |
| InfoNCE | 3.908 | 31 |
| InfoNCE | 3.915 | 32 |
| InfoNCE | 3.874 | 33 |
| InfoNCE | 3.882 | 34 |
| InfoNCE | 3.930 | 35 |
| InfoNCE | 3.900 | 36 |
| InfoNCE | 3.896 | 37 |
| InfoNCE | 3.907 | 38 |
| InfoNCE | 3.952 | 39 |
| InfoNCE | 3.915 | 40 |
| InfoNCE | 3.918 | 41 |
| InfoNCE | 3.885 | 42 |
| InfoNCE | 3.902 | 43 |
| InfoNCE | 3.893 | 44 |
| InfoNCE | 3.892 | 45 |
| InfoNCE | 3.903 | 46 |
| InfoNCE | 3.904 | 47 |
| InfoNCE | 3.907 | 48 |
| InfoNCE | 3.877 | 49 |
| InfoNCE | 3.906 | 50 |
| InfoNCE | 3.937 | 51 |
| InfoNCE | 3.886 | 52 |
| InfoNCE | 3.927 | 53 |
| InfoNCE | 3.861 | 54 |
| InfoNCE | 3.875 | 55 |
| InfoNCE | 3.894 | 56 |
| InfoNCE | 3.887 | 57 |
| InfoNCE | 3.892 | 58 |
| InfoNCE | 3.861 | 59 |
| InfoNCE | 3.901 | 60 |
Assumptions
- The representation uses several directions — The first principal direction holds 59% 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.
A SCARF contrastive encoder turned 344 rows (6 features) into 8-dimensional representations (final InfoNCE loss 3.901); 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 InfoNCE loss
- 3.901
- Trustworthiness (k = 10)
- 0.9807
- Alignment (lower = views closer)
- 1.049
- Uniformity (lower = more spread)
- −1.514
- 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 59% 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.
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Penguins probeml_penguins · features: island, bill_len, bill_dep, flipper_len, body_mass, sex · label: species
- Iris tanh full batchml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
- Pima no labelml_pima · features: npreg, glu, bp, skin, bmi, ped, age
- Iris simsiamml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
- Penguins barlowml_penguins · features: island, bill_len, bill_dep, flipper_len, body_mass, sex · label: species
- Pima vicregml_pima · features: npreg, glu, bp, skin, bmi, ped, age
- Iris swav full batchml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
- Iris byol full batchml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
In the guides
Where it sits in the decision guides
- Representation visualization (t-SNE, UMAP) · DS & ML Decision Guide · Describe — summarize and visualize
- Representation learning (autoencoders, contrastive) · DS & ML Decision Guide · Discover — find structure without labels
What you need
- Featuresnumeric / categorical / boolean · 2–500 columns
- Columns used to describe each row. Numbers are standardized; categories become indicator columns.
- Label (color and probe only)categorical / boolean · 0–1 column
- Optional. Colors the map and scores how often nearest neighbors share it; never used in training.
Choices you make
model
- Representation sizedefault 8
Coordinates per row in the learned representation; the map shows its first two principal components.
- Encoder layers (units)default 64
Units in each hidden layer of the encoder, input side first.
- Activationdefault relu
Nonlinearity in the encoder's and head's hidden layers.
- ReLU(default) — Passes positive signals and zeroes the rest; trains fast and suits most networks.
- tanh — An S-shaped unit with outputs from −1 to 1; a steady choice for small networks on scaled inputs.
- Sigmoid (logistic) — An S-shaped unit with outputs from 0 to 1; trains slowly in deep networks, so keep it for shallow ones.
- Corruption ratedefault 0.6
Share of each row's features replaced by values from random other rows in its corrupted view.
- Objectivedefault infonce
The loss that trains the encoder on each row and its corrupted view. InfoNCE contrasts rows with each other; the others need no negative rows.
- InfoNCE (SCARF)(default) — Each row must pick out its own corrupted view among the other rows' views in the batch.
- SimSiam — A small predictor maps one view onto the other, whose side gets no gradient (stop-gradient). No negative rows.
- Barlow Twins — Pushes the two views' cross-correlation matrix toward the identity: matching coordinates agree, different ones don't repeat each other.
- VICReg — Keeps the two views close (invariance), every coordinate spread out (variance) and coordinates uncorrelated (covariance).
- SwAV — Assigns rows to learned prototypes in balanced groups (Sinkhorn) and predicts one view's group from the other view.
- BYOL — A predictor learns to match a slowly moving target copy of the encoder; the target follows the trained network after every step. No negative rows.
- Temperature (τ)default 1
Divides the cosine similarities in the InfoNCE loss; lower values punish near-miss negatives harder.
- Redundancy weight (λ)default 0.005
Barlow Twins' weight on the off-diagonal cross-correlations; larger values push coordinates harder toward carrying different information.
- Prototypesdefault 16
SwAV's learned cluster centers; rows are split evenly among them in every batch. Each row's nearest prototype is saved with the representation.
- Target momentum (τ)default 0.996
How slowly BYOL's target follows the trained network at the start; it rises to 1 by the last step (the paper's 0.996). Short runs move more with 0.99 or lower.
- Epochsdefault 200
Training passes over the data.
- Learning ratedefault 0.001
Adam's step size.
- Batch sizedefault 128
Rows per step; the other rows' views in the batch are the negatives, so larger batches give a harder task.
Advanced
- Invariance weightdefault 25
VICReg's weight on the mean squared distance between a row's two views (the paper's 25).
- Variance weightdefault 25
VICReg's weight on the hinge that keeps each coordinate's standard deviation near 1 across the batch (the paper's 25).
- Covariance weightdefault 1
VICReg's weight on the squared covariances between different coordinates (the paper's 1).
- Prototype temperature (τ)default 0.1
Divides the prototype scores before the softmax in SwAV's swapped prediction (the paper's 0.1).
- Sinkhorn εdefault 0.05
Smoothing of SwAV's balanced assignments; smaller values give harder assignments (the paper's 0.05).
- Sinkhorn iterationsdefault 3
Row and column normalization rounds that balance SwAV's assignments (the paper's 3).
- L2 penalty (λ)default 0
Adds ½·λ·Σw² over the weight matrices to the loss.
- Optimizerdefault default
How the weights are updated. The method's own choice is the usual one.
- Method's own(default) — Adam or AdamW, as the method describes; the usual choice.
- Adam — Adam without decoupled weight decay (an AdamW method's weight decay is then not applied).
- AdamW — Adam with decoupled weight decay; on an Adam method it adds decay 0.01 on weight matrices.
- SGD with momentum — Plain gradient steps with momentum 0.9; often needs a larger learning rate and a schedule.
- Learning-rate scheduledefault none
How the learning rate changes over training.
- Constant(default) — The same learning rate every epoch (the method's default).
- Cosine — Falls smoothly from the learning rate toward 0 over the epochs.
- Step — Divides the learning rate by 10 after each third of the epochs.
- One cycle — Rises from a 25th of the learning rate to the full rate over the first 30% of steps, then falls far below it.
- Reduce on plateau — Divides the learning rate by 10 after 10 epochs without improvement in the validation loss.
- Warm-up epochsdefault 0
Epochs at the start that ramp the learning rate up linearly; 0 = no warm-up.
- Gradient clippingdefault 0
Largest gradient size (L2 norm over all weights) before a step; larger gradients are scaled down. 0 = off.
- Weight average (EMA)default 0
Keeps a moving average of the weights (for example 0.99) and uses it for validation and the result. 0 = off.
- Weight average from epoch (SWA)default 0
Averages the weights at the end of every epoch from this one on and returns the average. 0 = off; not with EMA.
- Record every stepdefault off
Saves the loss, learning rate and gradient size after every batch in the training history, not only per epoch.
- Compute profiledefault parity
Where and how precisely the network trains. Parity matches the other engine; the faster profiles can give slightly different numbers.
- Parity(default) — Double precision on one CPU thread: the same numbers in Python and R, run after run (the default).
- Faster CPU — Single precision on all performance cores; repeatable on this Mac, results differ slightly from Parity.
- Apple GPU — Single precision on the Apple GPU (macOS 15 or later); results can differ slightly. Falls back to Faster CPU without a GPU.
- Checkpoint every (epochs)default —
Saves the training state this often and when training ends, so a stopped run can resume where it was. Automatic saves about every 30 seconds; 0 = off. Each save holds the weights and the optimizer's state, so a large text encoder tuned on every layer can take 1–2 GB per fold.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
The representation uses several directions
If one principal direction holds over 90% of the variance, the encoder has collapsed most rows onto a line.
- If violated → PCA map — A linear map cannot collapse the way a contrastive encoder can, and it shows how much structure the raw columns already have. Changes the question: Linear principal components instead of a learned nonlinear representation.
Neighbors share the label
With a label: nearest neighbors in the representation should share it about as often as in the raw columns.
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- n_features
- How many independent units the analysis used; it sets precision and power.
- embedding_dim
- Learning representations without labels by pulling two views of the same row together and pushing other rows' views away.
- final_loss
- A loss that asks each row to pick out its own corrupted view among the views of every row in the batch.
- epochs_run
- Stopping training when a score on held-back rows has stopped improving for a set number of rounds.
- trustworthiness
- A 0–1 score for whether rows that look close on a map are really close in the data.
- alignment
- Two checks on normalized representations — views of a row should sit close (alignment) while rows spread out (uniformity).
- uniformity
- Two checks on normalized representations — views of a row should sit close (alignment) while rows spread out (uniformity).
- top_pc_share
- A learned representation that uses only one or a few directions, so most of its coordinates repeat the same information.
- probe_acc
- How often a row's nearest neighbors in a representation share its label — a check that the representation kept the label.
- probe_acc_raw
- How often a row's nearest neighbors in a representation share its label — a check that the representation kept the label.
Per group, level or term: emb_check[<dim>], loss_part[<part>], cc_diag_mean, cc_offdiag_rms, prototypes_used, target_gap
Python and R
Python and R use different algorithms; results agree in substance (relative tolerance 1e-6). Python uses torch, codesplash; R uses torch, codesplashr.
Default traps between the two languages
- Lab tier. Both engines run the codesplash twin (codesplash.deep.generative.fit_scarf ↔ codesplashr::cs_deep_fit_scarf): the same encoder and head on LibTorch in double precision on one thread, initial weights, feature choice and donor rows from the shared Wichmann–Hill stream, Adam written out with torch's arithmetic. Python's and R's torch ship different LibTorch builds, so single kernels differ by an ulp or two from the first step.
- InfoNCE training amplifies those ulps: on two fixtures every value still agrees to 1e-12 (measured), but on Pima the losses drift apart from about epoch 11 and by the default 200 epochs the per-row coordinates differ (their checksums are not compared), while the final loss (4e-4), trustworthiness (3e-3), alignment (1.3e-2) and uniformity (3e-4) agree within the bands stated here (measured differences in brackets).
- The probe is leave-one-out 5-nearest-neighbor accuracy on at most 1,000 evenly spaced rows (ties: the nearest neighbor's label among the tied ones), not the linear probe of the SCARF paper.
- Objectives other than InfoNCE (Stage 12.10) run the codesplash twin codesplash.deep.ssl.fit_ssl ↔ codesplashr::cs_deep_fit_ssl on the same encoder, head, views and draws. They are written for tables, not images: the second view is SCARF's corrupted row (the first is the row itself), the projection head has no batch normalization, the SimSiam predictor has no bottleneck, SwAV uses one view pair per row (no multi-crop), its prototypes are normalized inside the forward pass and train from the first epoch. Each row's SwAV prototype is the first of the scores within 1e-12 of its best, so last-digit differences never flip an assignment.
- BYOL (Stage 12.10, gap stream G-BYOL) runs in the same twin (fit_ssl ↔ cs_deep_fit_ssl): SimSiam's predictor (emb → emb → emb, seed + 2); a target network that starts as a copy of the encoder and head and moves after every optimizer step, ξ ← τ·ξ + (1 − τ)·θ, with the paper's cosine schedule τ = 1 − (1 − τ_base)·(cos(πk/K) + 1)/2 over K = epochs × steps per epoch; the paper's symmetrized squared error between unit-length prediction and target vectors. No batch normalization in the head or predictor (tables, not images). The target is the trainer's extra state (trainer.set_extra_state ↔ cs_deep_trainer_set_extra_state), so checkpoints save it and a resumed run equals the uninterrupted one.
The exact script CodeSplash ran for example “Penguins probe” · 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 93f6670c35f62417
# 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.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_probe/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))
# %% SCARF (PyTorch, float64, one thread): corrupt round(c·P) features per row from other rows, InfoNCE on the projections
HIDDEN = [int(u) for u in [32]]
EMB = 8
fit = gen.fit_scarf(
X, groups, HIDDEN, EMB,
activation="relu",
corruption=0.6,
temperature=1,
epochs=60,
lr=0.001,
batch_size=64,
weight_decay=0,
seed=42,
)
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_probe/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"]]})
history.to_parquet(os.path.join(out, "history.parquet"), index=False)
# %% Result
values = {
"n": len(rows),
"n_features": len(groups),
"embedding_dim": EMB,
"final_loss": float(fit["history"][-1]["loss"]),
"epochs_run": int(fit["epochs_run"]),
"trustworthiness": trust,
"alignment": float(fit["alignment"]),
"uniformity": unif,
"top_pc_share": top_share,
"probe_acc": probe,
"probe_acc_raw": probe_raw,
}
for j in range(EMB):
values[f"emb_check[{j + 1}]"] = csembed.checksum(E[:, j], rows)
pick = csembed.sample_rows(len(rows), 5000)
grp = [("All rows" if LABEL is None else ("(missing)" if pd.isna(v) else str(v))) for v in (df[LABEL].iloc[rows[pick]] if LABEL else [None] * len(pick))]
charts = [cs.chart("map", "cluster-scatter", "Contrastive representation (principal components 1 and 2)", {
"x": cs.col("Component 1", P2[pick, 0], "numeric"),
"y": cs.col("Component 2", P2[pick, 1], "numeric"),
"cluster": cs.col(LABEL or "Group", grp, "categorical"),
}, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown.")]
ep = [h["epoch"] for h in fit["history"]]
charts.append(cs.chart("training", "training-components", "InfoNCE loss by epoch", {
"x": cs.col("Epoch", ep, "numeric"),
"value": cs.col("Loss", [h["loss"] for h in fit["history"]], "numeric"),
"component": cs.col("Part", ["InfoNCE"] * len(ep), "categorical"),
}))
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 SCARF contrastive encoder turned {len(rows)} rows ({len(groups)} features) into {EMB}-dimensional representations "
f"(final InfoNCE 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": "Final InfoNCE 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"},
],
})
The exact script CodeSplash ran for example “Penguins probe” · 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 93f6670c35f62417
# 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_probe/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
# %% SCARF (torch for R, float64, one thread): corrupt round(c * P) features per row from other rows, InfoNCE on the projections
HIDDEN <- as.integer(unlist(c(32)))
EMB <- as.integer(8)
fit <- cs_deep_fit_scarf(
X, groups, HIDDEN, EMB,
activation = "relu",
corruption = 0.6,
temperature = 1,
epochs = as.integer(60),
lr = 0.001,
batch_size = 64,
weight_decay = 0,
seed = 42
)
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_probe/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)))
nanoparquet::write_parquet(hist, file.path(out, "history.parquet"))
# %% Result
values <- list(
n = length(rows), n_features = length(groups), embedding_dim = EMB, final_loss = hist$loss[nrow(hist)],
epochs_run = fit$epochs_run, trustworthiness = trust, alignment = fit$alignment, uniformity = unif,
top_pc_share = top_share, probe_acc = probe, probe_acc_raw = probe_raw
)
for (j in seq_len(EMB)) values[[sprintf("emb_check[%d]", j)]] <- cs_ml_checksum(E[, j], rows)
pick <- cs_ml_sample_rows(length(rows), 5000)
grp <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
g <- df[[LABEL]][rows[pick] + 1L]
ifelse(is.na(g), "(missing)", as.character(g))
}
charts <- list(cs_chart("map", "cluster-scatter", "Contrastive representation (principal components 1 and 2)", list(
x = cs_col("Component 1", P2[pick, 1], "numeric"),
y = cs_col("Component 2", P2[pick, 2], "numeric"),
cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, grp, "categorical")
), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ","))))
charts[[2]] <- cs_chart("training", "training-components", "InfoNCE loss by epoch", list(
x = cs_col("Epoch", hist$epoch, "numeric"),
value = cs_col("Loss", hist$loss, "numeric"),
component = cs_col("Part", rep("InfoNCE", nrow(hist)), "categorical")
))
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 SCARF contrastive encoder turned %d rows (%d features) into %d-dimensional representations (final InfoNCE loss %.3f); neighborhoods are kept with trustworthiness %.3f.",
length(rows), length(groups), EMB, 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 = "Final InfoNCE 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")
)
))
Sources
- Bahri D, Jiang H, Tay Y, Metzler D (2022). SCARF: self-supervised contrastive learning using random feature corruption. ICLR 2022.
- van den Oord A, Li Y, Vinyals O (2018). Representation learning with contrastive predictive coding. arXiv:1807.03748 (InfoNCE).
- Chen T, Kornblith S, Norouzi M, Hinton G (2020). A simple framework for contrastive learning of visual representations. ICML 2020.
- Wang T, Isola P (2020). Understanding contrastive representation learning through alignment and uniformity on the hypersphere. ICML 2020.
- Chen X, He K (2021). Exploring simple Siamese representation learning. CVPR 2021 (SimSiam).
- Zbontar J, Jing L, Misra I, LeCun Y, Deny S (2021). Barlow Twins: self-supervised learning via redundancy reduction. ICML 2021.
- Bardes A, Ponce J, LeCun Y (2022). VICReg: variance-invariance-covariance regularization for self-supervised learning. ICLR 2022.
- Caron M, Misra I, Mairal J, Goyal P, Bojanowski P, Joulin A (2020). Unsupervised learning of visual features by contrasting cluster assignments. NeurIPS 2020 (SwAV).
- Grill J-B, Strub F, Altché F, Tallec C, Richemond PH, Buchatskaya E, Doersch C, Pires BA, Guo ZD, Azar MG, Piot B, Kavukcuoglu K, Munos R, Valko M (2020). Bootstrap your own latent: a new approach to self-supervised learning. NeurIPS 2020 (BYOL).
From the CodeSplash method registry · discover.contrastive v1.3.0.