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
1 change: 1 addition & 0 deletions METHODS.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ Methods come in two forms:
| Barlow Twins | `barlow_twins` | `BarlowTwins` | `BarlowTwinsLoss` | — | [Zbontar et al., 2021](https://arxiv.org/abs/2103.03230) |
| SwAV | `swav` | `SwAV` | `SwAVLoss` | `OnlineQueue` | [Caron et al., 2020](https://arxiv.org/abs/2006.09882) |
| NNCLR | `nnclr` | `NNCLR` | `NTXEntLoss` | `OnlineQueue` | [Dwibedi et al., 2021](https://arxiv.org/abs/2104.14548) |
| ReSA | `resa` | `ReSA` | `ReSALoss` | `TeacherStudent†` | [Weng et al., 2025](https://arxiv.org/abs/2501.18452) |
| DINO | `dino` | `DINO` | `DINOv1Loss` | `TeacherStudent†` | [Caron et al., 2021](https://arxiv.org/abs/2104.14294) |
| DINOv2 | `dinov2` | `DINOv2` | `DINOv2Loss`, `iBOTPatchLoss` | `TeacherStudent†` | [Oquab et al., 2024](https://arxiv.org/abs/2304.07193) |
| BEiT | — | `BEiT` | — | — | [Bao et al., 2022](https://arxiv.org/abs/2106.08254) |
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -778,6 +778,7 @@ spt.set(default_loggers={"registry": False})
| Barlow Twins | `forward.barlow_twins` | `BarlowTwinsLoss` | Cross-correlation matrix alignment to identity |
| SwAV | `forward.swav` | `SwAVLoss` | Online clustering with Sinkhorn-Knopp normalization |
| NNCLR | `forward.nnclr` | `NTXEntLoss` | Nearest-neighbor contrastive learning |
| ReSA | `forward.resa` | `ReSALoss` | Contrastive learning with Sinkhorn self-assigned soft targets |
| DINO | `forward.dino` | `DINOv1Loss` | Self-distillation with multi-crop and centering |
| DINOv2 | `forward.dinov2` | `DINOv2Loss`, `iBOTPatchLoss` | DINO + iBOT masked patch prediction |

Expand Down
9 changes: 9 additions & 0 deletions RELEASES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,15 @@ Unreleased
mix ``(1 - lamb) * invariance + lamb * visreg``. Registered in
``stable_pretraining.methods`` and ``METHODS.md``, with an Imagenette
ViT-S/16 benchmark under ``benchmarks/imagenet10/visreg-vit-small.py``.
- ``ReSA`` (Representation Self-Assignment): contrastive learning whose targets
are soft labels built by Sinkhorn-Knopp from the encoder's own
student-teacher similarities, per Weng et al., "Clustering Properties of
Self-Supervised Learning" (ICML 2025). Adds ``ReSALoss``, the ``resa``
forward function and the ``ReSA`` method class, registered in
``stable_pretraining``, ``stable_pretraining.methods`` and ``METHODS.md``,
with ResNet-18 benchmarks under ``benchmarks/cifar10/resa-resnet18.py`` and
``benchmarks/cifar100/resa-resnet18.py`` and the paper's evaluation in
``benchmarks/cifar10/resa-resnet18-eval.py``.

**Discoverability improvements**

Expand Down
11 changes: 11 additions & 0 deletions THIRD_PARTY_NOTICES.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,14 @@ scale with a lower floor, FP32-or-higher affine arithmetic and log determinants,
diagnostics, activation checkpointing, and checkpoint configuration validation.
This port uses its own state-dict layout; existing upstream and deepstats
checkpoints require an explicit conversion and cannot be loaded directly.

## ReSA reference implementation

`stable_pretraining/tests/unit/test_resa.py` contains a single-process reduction of
the ReSA loss and Sinkhorn-Knopp normalization from
[winci-ai/resa_cifar](https://github.com/winci-ai/resa_cifar) (`method/base.py` and
`method/resa.py`), commit `bc5d70a48ed9`, distributed under Apache-2.0 (Copyright
(c) Winci). The tests use it only as a reference to check that `ReSALoss` matches
the official loss and gradients. The full license is in
`stable_pretraining/tests/unit/licenses/RESA_CIFAR_LICENSE`. Tests are not included
in built distributions.
12 changes: 12 additions & 0 deletions benchmarks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,18 @@ python benchmarks/cifar10/barlow-resnet18.py

# NNCLR
python benchmarks/cifar10/nnclr-resnet18.py

# ReSA, then its paper-protocol linear and 5-NN evaluation
python benchmarks/cifar10/resa-resnet18.py
python benchmarks/cifar10/resa-resnet18-eval.py --ckpt path/to/last.ckpt
```

### CIFAR-100 Benchmarks

```bash
# ReSA (the CIFAR-10 recipe with --dataset cifar100)
python benchmarks/cifar100/resa-resnet18.py
python benchmarks/cifar10/resa-resnet18-eval.py --ckpt path/to/last.ckpt --dataset cifar100
```

## Notes
Expand Down
152 changes: 152 additions & 0 deletions benchmarks/cifar10/resa-resnet18-eval.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
"""Evaluate a ReSA checkpoint from ``resa-resnet18.py`` with the paper's protocol.

Follows the official evaluation (https://github.com/winci-ai/resa_cifar,
``eval/evaluate.py``): the teacher backbone embeds the un-augmented training and
test images; 5-NN accuracy is a majority vote over Euclidean distances; a linear
classifier is trained on the frozen features with Adam (learning rate 1e-2
decaying exponentially to 1e-6 over 500 epochs, batch 1000, weight decay 5e-6)
and scored after the last epoch.

Usage:
python benchmarks/cifar10/resa-resnet18-eval.py --ckpt path/to/last.ckpt
python benchmarks/cifar10/resa-resnet18-eval.py --ckpt path/to/last.ckpt --dataset cifar100
"""

import argparse
import json
import sys
from pathlib import Path

import torch
import torch.nn as nn
import torchvision
from torchvision import transforms as T

import stable_pretraining as spt

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

# The official evaluation normalizes CIFAR-100 with these CIFAR-10 statistics too.
MEAN, STD = (0.4914, 0.4822, 0.4465), (0.247, 0.243, 0.261)
DATASETS = {
"cifar10": torchvision.datasets.CIFAR10,
"cifar100": torchvision.datasets.CIFAR100,
}


def load_teacher(ckpt_path):
backbone = spt.backbone.from_torchvision(
"resnet18", low_resolution=True, weights=None
)
backbone.fc = nn.Identity()
checkpoint = torch.load(ckpt_path, map_location="cpu", weights_only=False)
prefix = "backbone.teacher."
state = {
k[len(prefix) :]: v
for k, v in checkpoint["state_dict"].items()
if k.startswith(prefix)
}
backbone.load_state_dict(state)
return backbone, checkpoint.get("epoch")


@torch.no_grad()
def encode(model, dataset, device, num_workers):
loader = torch.utils.data.DataLoader(
dataset, batch_size=1000, num_workers=num_workers
)
features, labels = [], []
for x, y in loader:
features.append(model(x.to(device)).float())
labels.append(y.to(device))
return torch.cat(features), torch.cat(labels)


@torch.no_grad()
def knn_accuracy(x_train, y_train, x_test, y_test, k=5):
num_classes = int(y_train.max()) + 1
correct = 0
for i in range(0, len(x_test), 1000):
dist = torch.cdist(x_test[i : i + 1000], x_train)
nearest = dist.topk(k, dim=1, largest=False).indices
votes = nn.functional.one_hot(y_train[nearest], num_classes).sum(1)
# argmax keeps the smallest label among ties, as in the official code.
correct += (votes.argmax(1) == y_test[i : i + 1000]).sum().item()
return correct / len(x_test)


def linear_accuracy(x_train, y_train, x_test, y_test, epochs=500):
lr_start, lr_end = 1e-2, 1e-6
num_classes = int(y_train.max()) + 1
classifier = nn.Linear(x_train.shape[1], num_classes).to(x_train.device)
optimizer = torch.optim.Adam(
classifier.parameters(), lr=lr_start, weight_decay=5e-6
)
scheduler = torch.optim.lr_scheduler.ExponentialLR(
optimizer, gamma=(lr_end / lr_start) ** (1 / epochs)
)
criterion = nn.CrossEntropyLoss()
for _ in range(epochs):
for idx in torch.randperm(len(x_train), device=x_train.device).view(-1, 1000):
optimizer.zero_grad()
criterion(classifier(x_train[idx]), y_train[idx]).backward()
optimizer.step()
scheduler.step()
with torch.no_grad():
top5 = classifier(x_test).topk(5, dim=1).indices
return {
"linear_top1": (top5[:, :1] == y_test[:, None]).any(1).float().mean().item(),
"linear_top5": (top5 == y_test[:, None]).any(1).float().mean().item(),
}


def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--ckpt", required=True)
parser.add_argument("--dataset", choices=sorted(DATASETS), default="cifar10")
parser.add_argument("--num-workers", type=int, default=8)
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--out", default=None, help="also write the results as JSON")
args = parser.parse_args()

torch.manual_seed(args.seed)
if torch.cuda.is_available():
device = "cuda"
elif torch.backends.mps.is_available():
device = "mps"
else:
device = "cpu"
model, epoch = load_teacher(args.ckpt)
model = model.to(device).eval()

root = str(get_data_dir(args.dataset))
transform = T.Compose([T.ToTensor(), T.Normalize(MEAN, STD)])
x_train, y_train = encode(
model,
DATASETS[args.dataset](root, train=True, transform=transform, download=True),
device,
args.num_workers,
)
x_test, y_test = encode(
model,
DATASETS[args.dataset](root, train=False, transform=transform, download=True),
device,
args.num_workers,
)

results = {
"ckpt": args.ckpt,
"dataset": args.dataset,
"epoch": epoch,
"knn5": knn_accuracy(x_train, y_train, x_test, y_test),
**linear_accuracy(x_train, y_train, x_test, y_test),
}
print(json.dumps(results, indent=2))
if args.out:
with open(args.out, "w") as f:
json.dump(results, f, indent=2)


if __name__ == "__main__":
main()
Loading
Loading