Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions METHODS.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ Methods come in two forms:
| SALT | — | `SALT` | — | — | [Li et al., 2025](https://arxiv.org/pdf/2509.24317) |
| SimMIM | — | `SimMIM` | — | — | [Xie et al., 2022](https://arxiv.org/abs/2111.09886) |
| SimSiam | — | `SimSiam` | — | — | [Chen & He, 2021](https://arxiv.org/abs/2011.10566) |
| SpectralCL | `spectral` | `SpectralCL` | `SpectralContrastiveLoss` | — | [HaoChen et al., 2021](https://arxiv.org/abs/2106.04156) |
| TiCO | — | `TiCO` | — | — | [Zhu et al., 2022](https://arxiv.org/abs/2206.10698) |
| VICRegL | — | `VICRegL` | `VICRegLoss` | — | [Bardes et al., 2022](https://arxiv.org/abs/2210.01571) |
| VISReg | — | `VISReg` | — | — | [Wu et al., 2026](https://arxiv.org/abs/2606.02572) |
Expand Down Expand Up @@ -104,6 +105,7 @@ All loss classes are importable from `stable_pretraining.losses`:
| Loss | Methods that use it |
|------|-------------------|
| `NTXEntLoss` | SimCLR, NNCLR, MoCov2, MoCov3 |
| `SpectralContrastiveLoss` | SpectralCL |
| `BYOLLoss` | BYOL |
| `VICRegLoss` | VICReg, VICRegL |
| `BarlowTwinsLoss` | Barlow Twins |
Expand Down
15 changes: 15 additions & 0 deletions RELEASES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@ Unreleased

**New method**

- ``SpectralCL`` (Spectral Contrastive Learning): contrastive learning with the
spectral contrastive loss, ``-2 E[z . z+] + E[(z . z-)^2]``, per HaoChen et al.,
"Provable Guarantees for Self-Supervised Deep Learning with Spectral
Contrastive Loss" (NeurIPS 2021). It needs no temperature, momentum encoder,
or stop-gradient; embeddings are confined to a ball of radius ``sqrt(mu)``
and the loss is divided by ``mu``, as in the authors' code. It accepts both
tensors and the batch dicts of ``Module``, so it trains directly with
``Trainer`` / ``Manager``. Registered in ``stable_pretraining.methods``,
exported as ``stable_pretraining.SpectralCL``, and listed in ``METHODS.md``.
The loss is available as ``stable_pretraining.losses.SpectralContrastiveLoss``
and the composable forward as ``stable_pretraining.forward.spectral``.
Includes stable gradients for tiny embeddings, real two-process CPU/gloo DDP
gradient tests, and a CIFAR-10 ResNet-18 benchmark under
``benchmarks/cifar10/spectral-resnet18.py`` that seeds initialization and uses
the same projector for the spectral and NT-Xent objectives.
- ``PMSN`` (Prior Matching for Siamese Networks): extends ``MSN`` by replacing
its uniform-prior mean-entropy regulariser with a KL-divergence term against
an arbitrary prior distribution over prototypes (power-law by default,
Expand Down
198 changes: 198 additions & 0 deletions benchmarks/cifar10/spectral-resnet18.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
"""Spectral contrastive learning on CIFAR-10, with a SimCLR control.

Follows the CIFAR-10 recipe of the authors' code for HaoChen et al., "Provable
Guarantees for Self-Supervised Deep Learning with Spectral Contrastive Loss"
(NeurIPS 2021): CIFAR-style ResNet-18, a BatchNorm MLP projector
(512 -> 2048 -> 1000), SGD with momentum 0.9 and weight decay 5e-4, batch size
512, a learning rate of ``0.03 * 512 / 256`` with 10 warmup epochs and a cosine
decay to zero, and the SimSiam augmentations. The paper trains for 800 epochs.

Settings are read from environment variables: ``MAX_EPOCHS`` (default 200),
``MU`` (spectral loss radius squared, default 1), ``SEED`` (default 0) and
``LOSS`` (``spectral`` or ``simclr``). ``LOSS=simclr`` uses the SimCLR NT-Xent
loss at temperature 0.5 with the same backbone and projector, including the
trainable bias of the final BatchNorm. Both objectives use the same seed
before initializing the model and online probe. This is a matched-architecture
loss comparison, not a reproduction of the standard SimCLR projector.

``SpectralCL`` is passed to ``spt.Manager`` as the training module itself: it
consumes the ``MultiViewTransform`` batch dicts through its own forward.
"""

import os
import sys
from pathlib import Path
from typing import Optional

import lightning as pl
import torch
import torch.nn as nn
import torchmetrics
import torchvision

import stable_pretraining as spt
from stable_pretraining.data import transforms


def build_model(
loss_name: str, mu: float = 1.0, optim: Optional[dict] = None
) -> spt.SpectralCL:
"""Build the same architecture for the spectral and NT-Xent objectives.

Args:
loss_name: ``"spectral"`` or ``"simclr"``.
mu: Spectral loss radius squared; unused by the NT-Xent objective.
optim: Optimizer configuration in the format of
:class:`~stable_pretraining.Module`, forwarded to ``SpectralCL``.

Returns:
The CIFAR-style ResNet-18 and shared BatchNorm projector, with the
selected loss. Call ``pl.seed_everything`` before construction to
reproduce initialization.

Raises:
ValueError: If ``loss_name`` is not a supported objective.
"""
if loss_name not in {"spectral", "simclr"}:
raise ValueError(f"LOSS must be 'spectral' or 'simclr', got {loss_name!r}")

backbone = spt.backbone.from_torchvision("resnet18", low_resolution=True)
backbone.fc = nn.Identity()
model = spt.SpectralCL(
encoder_name=backbone, projector_dims=(2048, 1000), mu=mu, optim=optim
)
if loss_name == "simclr":
# Replacing only the criterion keeps final-BN bias trainable in both runs.
model.spectral_loss = spt.losses.NTXEntLoss(temperature=0.5)
return model


def _view_transform():
return transforms.Compose(
transforms.RGB(),
transforms.RandomResizedCrop((32, 32), scale=(0.2, 1.0)),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ColorJitter(
brightness=0.4, contrast=0.4, saturation=0.4, hue=0.1, p=0.8
),
transforms.RandomGrayscale(p=0.2),
transforms.ToImage(**spt.data.static.CIFAR10),
)


def main() -> None:
seed = int(os.environ.get("SEED", 0))
pl.seed_everything(seed, workers=True)

sys.path.append(str(Path(__file__).parent.parent))
from utils import get_data_dir

# No per-epoch requeue checkpoint: this benchmark saves no checkpoints.
spt.set(requeue_checkpoint=False)

batch_size = 512
num_workers = int(os.environ.get("NUM_WORKERS", 8))
max_epochs = int(os.environ.get("MAX_EPOCHS", 200))
warmup_epochs = 10
mu = float(os.environ.get("MU", 1.0))
loss_name = os.environ.get("LOSS", "spectral")
base_lr = 0.03

train_transform = transforms.MultiViewTransform(
{"view_0": _view_transform(), "view_1": _view_transform()}
)
val_transform = transforms.Compose(
transforms.RGB(),
transforms.Resize((32, 32)),
transforms.ToImage(**spt.data.static.CIFAR10),
)

data_dir = get_data_dir("cifar10")
cifar_train = torchvision.datasets.CIFAR10(
root=str(data_dir), train=True, download=True
)
cifar_val = torchvision.datasets.CIFAR10(
root=str(data_dir), train=False, download=True
)

data = spt.data.DataModule(
train=torch.utils.data.DataLoader(
dataset=spt.data.FromTorchDataset(
cifar_train, names=["image", "label"], transform=train_transform
),
batch_size=batch_size,
num_workers=num_workers,
drop_last=True,
persistent_workers=num_workers > 0,
shuffle=True,
),
val=torch.utils.data.DataLoader(
dataset=spt.data.FromTorchDataset(
cifar_val, names=["image", "label"], transform=val_transform
),
batch_size=256,
num_workers=num_workers,
),
)

model = build_model(
loss_name,
mu,
optim={
"optimizer": {
"type": "SGD",
"lr": base_lr * batch_size / 256,
"momentum": 0.9,
"weight_decay": 5e-4,
},
"scheduler": {
"type": "LinearWarmupCosineAnnealing",
"peak_step": warmup_epochs / max_epochs,
"start_factor": 0.01,
"end_lr": 0.0,
"total_steps": len(data.train) * max_epochs,
},
"interval": "step",
},
)

trainer = pl.Trainer(
max_epochs=max_epochs,
num_sanity_val_steps=0,
callbacks=[
spt.callbacks.OnlineProbe(
model,
name="linear_probe",
input="embedding",
target="label",
probe=nn.Linear(model.embed_dim, 10),
loss=nn.CrossEntropyLoss(),
metrics={
"top1": torchmetrics.classification.MulticlassAccuracy(10),
"top5": torchmetrics.classification.MulticlassAccuracy(10, top_k=5),
},
),
spt.callbacks.OnlineKNN(
name="knn_probe",
input="embedding",
target="label",
queue_length=20000,
metrics={
"accuracy": torchmetrics.classification.MulticlassAccuracy(10)
},
input_dim=model.embed_dim,
k=10,
),
pl.pytorch.callbacks.LearningRateMonitor(logging_interval="step"),
],
logger=False,
precision="16-mixed",
enable_checkpointing=False,
)

manager = spt.Manager(trainer=trainer, module=model, data=data, seed=seed)
manager()


if __name__ == "__main__":
main()
20 changes: 20 additions & 0 deletions docs/source/api/forward.rst
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,26 @@ Or in Python code:
Available Forward Functions
---------------------------

Spectral Contrastive Learning
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. autofunction:: spectral

Compose the same dictionary training interface used by ``spt.SpectralCL`` with
custom components:

.. code-block:: python

import stable_pretraining as spt

module = spt.Module(
forward=spt.forward.spectral,
backbone=backbone,
projector=projector,
spectral_loss=spt.losses.SpectralContrastiveLoss(mu=10.0),
optim={"optimizer": {"type": "SGD", "lr": 0.06}},
)

SimCLR
~~~~~~

Expand Down
1 change: 1 addition & 0 deletions docs/source/api/losses.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ stable_pretraining.losses
:template: myclass_template.rst

NTXEntLoss
SpectralContrastiveLoss
NegativeCosineSimilarity
VICRegLoss
BarlowTwinsLoss
1 change: 1 addition & 0 deletions docs/source/api/methods.rst
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ or by bootstrapping without explicit negatives.
SimSiam
PIRL
TiCO
SpectralCL

Feature Redundancy Reduction
-----------------------------
Expand Down
2 changes: 2 additions & 0 deletions stable_pretraining/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ def emit(self, record):
"MAE": ("stable_pretraining.methods.mae", "MAE"),
"NNCLR": ("stable_pretraining.methods.nnclr", "NNCLR"),
"SimCLR": ("stable_pretraining.methods.simclr", "SimCLR"),
"SpectralCL": ("stable_pretraining.methods.spectral_cl", "SpectralCL"),
"SwAV": ("stable_pretraining.methods.swav", "SwAV"),
"VICReg": ("stable_pretraining.methods.vicreg", "VICReg"),
}
Expand Down Expand Up @@ -489,6 +490,7 @@ def __dir__() -> list[str]:
"MAE",
"NNCLR",
"SimCLR",
"SpectralCL",
"SwAV",
"VICReg",
"log",
Expand Down
1 change: 1 addition & 0 deletions stable_pretraining/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ from .methods.dinov2 import DINOv2 as DINOv2
from .methods.mae import MAE as MAE
from .methods.nnclr import NNCLR as NNCLR
from .methods.simclr import SimCLR as SimCLR
from .methods.spectral_cl import SpectralCL as SpectralCL
from .methods.swav import SwAV as SwAV
from .methods.vicreg import VICReg as VICReg

Expand Down
60 changes: 60 additions & 0 deletions stable_pretraining/forward.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
Available forward functions:
- ``supervised`` — standard supervised training
- ``simclr`` — SimCLR contrastive learning
- ``spectral`` — spectral contrastive learning
- ``byol`` — BYOL momentum self-distillation
- ``vicreg`` — VICReg variance-invariance-covariance regularization
- ``barlow_twins`` — Barlow Twins cross-correlation alignment
Expand Down Expand Up @@ -256,6 +257,65 @@ def simclr(self, batch: dict[str, Any], stage: str) -> dict[str, torch.Tensor]:
return out


def spectral(self, batch: dict[str, Any], stage: str) -> dict[str, torch.Tensor]:
"""Compute spectral contrastive learning outputs from a batch dictionary.

Args:
self: Module instance with ``backbone``, ``projector``, and
``spectral_loss`` attributes. The loss is typically
:class:`~stable_pretraining.losses.SpectralContrastiveLoss`.
batch: Two view dictionaries under ``"views"`` or arbitrary named keys
during training. Evaluation accepts a single ``"image"`` batch or
multiple views. Each view may carry a ``"label"`` tensor.
stage: Lightning stage, used to name the loss metric.

Returns:
Dictionary with concatenated ``"embedding"`` tensors, ``"label"`` when
supplied, and a scalar ``"loss"`` during training.

Raises:
ValueError: If training does not receive exactly two views, or an
evaluation batch contains no images.

Note:
Non-view metadata such as the ``batch_idx`` injected by Module is
ignored. Evaluation uses only the backbone, without a projector or
distributed loss collective. This function also implements the batch
dictionary interface of :class:`~stable_pretraining.SpectralCL`.
"""
if "views" in batch:
views = list(batch["views"])
elif "image" in batch:
views = [batch]
else:
views = [v for v in batch.values() if isinstance(v, dict) and "image" in v]

if self.training and len(views) != 2:
raise ValueError(
f"SpectralCL training needs exactly 2 views per sample, got {len(views)}"
)
if not views:
raise ValueError("SpectralCL evaluation needs at least one image view")

embeddings = [self.backbone(view["image"]) for view in views]
out = {"embedding": torch.cat(embeddings, dim=0)}
if "label" in views[0]:
out["label"] = torch.cat([view["label"] for view in views], dim=0)
if self.training:
projections = [self.projector(embedding) for embedding in embeddings]
out["loss"] = self.spectral_loss(projections[0], projections[1])
if self._trainer is not None:
self.log(
f"{stage}/loss",
out["loss"],
on_step=True,
on_epoch=True,
sync_dist=True,
batch_size=embeddings[0].size(0),
)
return out


def byol(self, batch: dict[str, Any], stage: str) -> dict[str, torch.Tensor]:
"""Forward function for BYOL (Bootstrap Your Own Latent).

Expand Down
3 changes: 3 additions & 0 deletions stable_pretraining/losses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
SwAVLoss,
)

from .spectral import SpectralContrastiveLoss

# Multimodal losses
from .multimodal import CLIPLoss

Expand All @@ -44,6 +46,7 @@
"BarlowTwinsLoss",
"NTXEntLoss",
"SwAVLoss",
"SpectralContrastiveLoss",
"CLIPLoss",
# Reconstruction
"mae",
Expand Down
Loading
Loading