diff --git a/METHODS.md b/METHODS.md index a8d123535..fc1e6cd42 100644 --- a/METHODS.md +++ b/METHODS.md @@ -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) | diff --git a/README.md b/README.md index d9a1f46da..8d4e4ac02 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/RELEASES.rst b/RELEASES.rst index 9b10a58e6..5bd9b90f6 100644 --- a/RELEASES.rst +++ b/RELEASES.rst @@ -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** diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index b7fee6428..3512c011a 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -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. diff --git a/benchmarks/README.md b/benchmarks/README.md index 1064c847c..b8bcf12e6 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -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 diff --git a/benchmarks/cifar10/resa-resnet18-eval.py b/benchmarks/cifar10/resa-resnet18-eval.py new file mode 100644 index 000000000..da0e8a861 --- /dev/null +++ b/benchmarks/cifar10/resa-resnet18-eval.py @@ -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() diff --git a/benchmarks/cifar10/resa-resnet18.py b/benchmarks/cifar10/resa-resnet18.py new file mode 100644 index 000000000..02c3595f7 --- /dev/null +++ b/benchmarks/cifar10/resa-resnet18.py @@ -0,0 +1,271 @@ +"""ReSA training on CIFAR-10 or CIFAR-100 with a ResNet-18. + +Follows the official CIFAR recipe (https://github.com/winci-ai/resa_cifar). +Paper (Table 1, ResNet-18, 1000 epochs): CIFAR-10 93.53 linear / 93.02 k-NN, +CIFAR-100 72.21 / 66.83. + +Usage: + python benchmarks/cifar10/resa-resnet18.py + python benchmarks/cifar10/resa-resnet18.py --dataset cifar100 + python benchmarks/cifar10/resa-resnet18.py --epochs 2 --limit-train-batches 20 # smoke test +""" + +import argparse +import sys +from pathlib import Path + +import lightning as pl +import torch +import torch.nn as nn +import torchmetrics +import torchvision +from lightning.pytorch.callbacks import LearningRateMonitor, ModelCheckpoint +from torchvision.transforms import InterpolationMode + +import stable_pretraining as spt +from stable_pretraining.data import transforms +from stable_pretraining.forward import resa + +sys.path.append(str(Path(__file__).parent.parent)) +from utils import get_data_dir + +# Normalization statistics from the official code (src/transform.py). +STATS = { + "cifar10": {"mean": (0.4914, 0.4822, 0.4465), "std": (0.2470, 0.2435, 0.2616)}, + "cifar100": {"mean": (0.5071, 0.4865, 0.4409), "std": (0.2673, 0.2564, 0.2762)}, +} +DATASETS = { + "cifar10": (torchvision.datasets.CIFAR10, 10), + "cifar100": (torchvision.datasets.CIFAR100, 100), +} + + +def parse_args(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--dataset", choices=sorted(DATASETS), default="cifar10") + parser.add_argument("--epochs", type=int, default=1000) + parser.add_argument("--batch-size", type=int, default=256) + parser.add_argument( + "--lr", type=float, default=0.3, help="base learning rate, scaled by batch/256" + ) + parser.add_argument("--weight-decay", type=float, default=1e-4) + parser.add_argument("--warmup-epochs", type=int, default=2) + parser.add_argument("--temperature", type=float, default=0.4) + parser.add_argument("--ema", type=float, default=0.996, help="base EMA momentum") + parser.add_argument("--precision", default="16-mixed") + parser.add_argument("--num-workers", type=int, default=8) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument( + "--checkpoint-every", + type=int, + default=100, + help="also keep a checkpoint every N epochs (0 to disable)", + ) + parser.add_argument( + "--limit-train-batches", + type=int, + default=None, + help="cap batches per epoch, for smoke tests", + ) + parser.add_argument("--cache-dir", default=None, help="where runs are written") + return parser.parse_args() + + +class ReSADiagnostics(pl.Callback): + """Log per-epoch statistics of the soft labels. + + Each row of the soft-label matrix is one image's target distribution over + the batch. + + - ``diagonal_mass``: weight an image puts on itself (1 for one-hot targets). + - ``same_class_share``: fraction of the weight on other images that goes to + images of the same class (chance is about 1 / num_classes). + - ``target_entropy``: row entropy, a lower bound on the cross-entropy loss. + + Labels are used only for logging. Assumes a single process, so the soft + labels' columns are this batch's images. + """ + + def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx): + assignment = outputs.get("resa_assignment") + if assignment is None or "label" not in outputs: + return + n = assignment.shape[0] + labels = outputs["label"][:n] + idx = torch.arange(n, device=assignment.device) + off_diagonal = assignment.clone() + off_diagonal[idx, idx] = 0 + same_class = (labels[:, None] == labels[None, :]).to(assignment.dtype) + share = (off_diagonal * same_class).sum(1) / off_diagonal.sum(1).clamp_min( + 1e-12 + ) + pl_module.log_dict( + { + "train/resa_diagonal_mass": assignment[idx, idx].mean(), + "train/resa_same_class_share": share.mean(), + "train/resa_target_entropy": torch.special.entr(assignment) + .sum(1) + .mean(), + }, + on_step=False, + on_epoch=True, + ) + + +def main(): + args = parse_args() + if args.cache_dir: + spt.set(cache_dir=args.cache_dir) + stats = STATS[args.dataset] + dataset_cls, num_classes = DATASETS[args.dataset] + + weak = transforms.Compose( + transforms.RGB(), + transforms.RandomResizedCrop((32, 32), scale=(0.2, 1.0)), + transforms.RandomHorizontalFlip(p=0.5), + transforms.ToImage(**stats), + ) + strong = transforms.Compose( + transforms.RGB(), + transforms.RandomResizedCrop( + (32, 32), scale=(0.2, 1.0), interpolation=InterpolationMode.BICUBIC + ), + transforms.ColorJitter( + brightness=0.4, contrast=0.4, saturation=0.2, hue=0.1, p=0.8 + ), + transforms.RandomGrayscale(p=0.2), + transforms.RandomSolarize(threshold=128, p=0.2), + transforms.RandomHorizontalFlip(p=0.5), + transforms.ToImage(**stats), + ) + val_transform = transforms.Compose( + transforms.RGB(), + transforms.Resize((32, 32)), + transforms.ToImage(**stats), + ) + + data_dir = get_data_dir(args.dataset) + train_dataset = spt.data.FromTorchDataset( + dataset_cls(root=str(data_dir), train=True, download=True), + names=["image", "label"], + # The weak view comes first: ReSA builds its soft labels from view 0. + transform=transforms.MultiViewTransform([weak, strong]), + ) + val_dataset = spt.data.FromTorchDataset( + dataset_cls(root=str(data_dir), train=False, download=True), + names=["image", "label"], + transform=val_transform, + ) + loader_kwargs = dict( + batch_size=args.batch_size, + num_workers=args.num_workers, + persistent_workers=args.num_workers > 0, + pin_memory=torch.cuda.is_available(), + ) + train_dataloader = torch.utils.data.DataLoader( + train_dataset, drop_last=True, shuffle=True, **loader_kwargs + ) + val_dataloader = torch.utils.data.DataLoader(val_dataset, **loader_kwargs) + data = spt.data.DataModule(train=train_dataloader, val=val_dataloader) + + backbone = spt.backbone.from_torchvision( + "resnet18", low_resolution=True, weights=None + ) + backbone.fc = nn.Identity() + projector = nn.Sequential( + nn.Linear(512, 2048), + nn.BatchNorm1d(2048), + nn.ReLU(inplace=True), + nn.Linear(2048, 2048), + nn.BatchNorm1d(2048), + nn.ReLU(inplace=True), + nn.Linear(2048, 512), + nn.BatchNorm1d(512, affine=False), + ) + # TeacherStudentCallback updates the teacher every step but recomputes the + # momentum once per epoch; the official code recomputes it every iteration. + # They differ by at most ~6e-6 at 1000 epochs, so we keep the library's callback. + ema = dict(warm_init=True, base_ema_coefficient=args.ema, final_ema_coefficient=1.0) + + steps_per_epoch = len(train_dataloader) + if args.limit_train_batches: + steps_per_epoch = min(steps_per_epoch, args.limit_train_batches) + max_steps = args.epochs * steps_per_epoch + # The cosine phase divides by (max_steps - warmup_steps), so keep it non-empty. + warmup_steps = min(args.warmup_epochs * steps_per_epoch, max_steps - 1) + lr = args.lr * args.batch_size / 256 + module = spt.Module( + backbone=spt.TeacherStudentWrapper(backbone, **ema), + projector=spt.TeacherStudentWrapper(projector, **ema), + forward=resa, + resa_loss=spt.losses.ReSALoss(temperature=args.temperature), + optim={ + "optimizer": { + "type": "SGD", + "lr": lr, + "momentum": 0.9, + "weight_decay": args.weight_decay, + }, + "scheduler": { + "type": "LinearWarmupCosineAnnealingLR", + "warmup_steps": warmup_steps, + "max_steps": max_steps, + "warmup_start_lr": 0.0, + "eta_min": 0.1 * lr, + }, + "interval": "step", + }, + ) + + callbacks = [ + spt.callbacks.OnlineProbe( + module, + name="linear_probe", + input="embedding", + target="label", + probe=nn.Linear(512, num_classes), + loss=nn.CrossEntropyLoss(), + metrics={ + "top1": torchmetrics.classification.MulticlassAccuracy(num_classes), + "top5": torchmetrics.classification.MulticlassAccuracy( + num_classes, top_k=5 + ), + }, + ), + spt.callbacks.OnlineKNN( + name="knn_probe", + input="embedding", + target="label", + queue_length=20000, + metrics={ + "accuracy": torchmetrics.classification.MulticlassAccuracy(num_classes) + }, + input_dim=512, + k=10, + ), + ReSADiagnostics(), + LearningRateMonitor(logging_interval="epoch"), + ] + if args.checkpoint_every > 0: + callbacks.append( + ModelCheckpoint( + filename="epoch{epoch:04d}", + auto_insert_metric_name=False, + every_n_epochs=args.checkpoint_every, + save_top_k=-1, + ) + ) + + trainer = pl.Trainer( + max_epochs=args.epochs, + num_sanity_val_steps=0, + callbacks=callbacks, + precision=args.precision, + limit_train_batches=args.limit_train_batches, + ) + manager = spt.Manager(trainer=trainer, module=module, data=data, seed=args.seed) + manager() + + +if __name__ == "__main__": + main() diff --git a/benchmarks/cifar100/resa-resnet18.py b/benchmarks/cifar100/resa-resnet18.py new file mode 100644 index 000000000..a4714735f --- /dev/null +++ b/benchmarks/cifar100/resa-resnet18.py @@ -0,0 +1,19 @@ +"""ReSA training on CIFAR-100 with a ResNet-18. + +Runs the shared CIFAR recipe in ``benchmarks/cifar10/resa-resnet18.py`` with +``--dataset cifar100``; every other flag is passed through. Paper (Table 1, +ResNet-18, 1000 epochs): 72.21 linear / 66.83 k-NN. + +Usage: + python benchmarks/cifar100/resa-resnet18.py + python benchmarks/cifar100/resa-resnet18.py --epochs 2 --limit-train-batches 20 # smoke test +""" + +import runpy +import sys +from pathlib import Path + +if __name__ == "__main__": + recipe = Path(__file__).resolve().parents[1] / "cifar10" / "resa-resnet18.py" + sys.argv = [str(recipe), "--dataset", "cifar100", *sys.argv[1:]] + runpy.run_path(str(recipe), run_name="__main__") diff --git a/docs/source/api/forward.rst b/docs/source/api/forward.rst index accbccd09..2f091ace9 100644 --- a/docs/source/api/forward.rst +++ b/docs/source/api/forward.rst @@ -187,6 +187,43 @@ BYOL in_features: 4096 out_features: 256 +ReSA +~~~~ + +.. autofunction:: resa + +**Required Module Attributes:** + +- ``backbone``: ``TeacherStudentWrapper`` around the encoder +- ``projector``: ``TeacherStudentWrapper`` around the projector +- ``resa_loss``: ``ReSALoss`` instance + +**Key Features:** + +- Soft labels from Sinkhorn-Knopp on the student-teacher similarities of the + first view, which should be the weakly augmented one +- Cross-entropy between the soft labels and the cross-view projection + similarities; identity labels recover InfoNCE +- Returns the detached soft labels as ``resa_assignment`` for monitoring + +**Example Config:** + +.. code-block:: yaml + + module: + forward: stable_pretraining.forward.resa + backbone: + _target_: stable_pretraining.TeacherStudentWrapper + student: ... + base_ema_coefficient: 0.996 + projector: + _target_: stable_pretraining.TeacherStudentWrapper + student: ... + base_ema_coefficient: 0.996 + resa_loss: + _target_: stable_pretraining.losses.ReSALoss + temperature: 0.4 + VICReg ~~~~~~ diff --git a/docs/source/api/losses.rst b/docs/source/api/losses.rst index 0b487a840..17707cfd9 100644 --- a/docs/source/api/losses.rst +++ b/docs/source/api/losses.rst @@ -9,6 +9,7 @@ stable_pretraining.losses :template: myclass_template.rst NTXEntLoss + ReSALoss NegativeCosineSimilarity VICRegLoss BarlowTwinsLoss diff --git a/docs/source/api/methods.rst b/docs/source/api/methods.rst index d582fa39a..80643eb04 100644 --- a/docs/source/api/methods.rst +++ b/docs/source/api/methods.rst @@ -39,6 +39,7 @@ or by bootstrapping without explicit negatives. SimSiam PIRL TiCO + ReSA Feature Redundancy Reduction ----------------------------- diff --git a/docs/source/references.bib b/docs/source/references.bib index 60a02f87a..5d4cc2a6c 100644 --- a/docs/source/references.bib +++ b/docs/source/references.bib @@ -104,3 +104,10 @@ @article{caron2020unsupervised pages={9912--9924}, year={2020} } + +@inproceedings{weng2025clustering, + title={Clustering Properties of Self-Supervised Learning}, + author={Weng, Xi and An, Jianing and Ma, Xudong and Qi, Binhang and Luo, Jie and Yang, Xi and Dong, Jin Song and Huang, Lei}, + booktitle={International Conference on Machine Learning}, + year={2025} +} diff --git a/stable_pretraining/__init__.py b/stable_pretraining/__init__.py index 1438bed7e..b4182d79d 100644 --- a/stable_pretraining/__init__.py +++ b/stable_pretraining/__init__.py @@ -185,6 +185,7 @@ def emit(self, record): "DINOv2": ("stable_pretraining.methods.dinov2", "DINOv2"), "MAE": ("stable_pretraining.methods.mae", "MAE"), "NNCLR": ("stable_pretraining.methods.nnclr", "NNCLR"), + "ReSA": ("stable_pretraining.methods.resa", "ReSA"), "SimCLR": ("stable_pretraining.methods.simclr", "SimCLR"), "SwAV": ("stable_pretraining.methods.swav", "SwAV"), "VICReg": ("stable_pretraining.methods.vicreg", "VICReg"), @@ -488,6 +489,7 @@ def __dir__() -> list[str]: "DINOv2", "MAE", "NNCLR", + "ReSA", "SimCLR", "SwAV", "VICReg", diff --git a/stable_pretraining/__init__.pyi b/stable_pretraining/__init__.pyi index 3fce470c4..5c2049546 100644 --- a/stable_pretraining/__init__.pyi +++ b/stable_pretraining/__init__.pyi @@ -47,6 +47,7 @@ from .methods.dino import DINO as DINO from .methods.dinov2 import DINOv2 as DINOv2 from .methods.mae import MAE as MAE from .methods.nnclr import NNCLR as NNCLR +from .methods.resa import ReSA as ReSA from .methods.simclr import SimCLR as SimCLR from .methods.swav import SwAV as SwAV from .methods.vicreg import VICReg as VICReg diff --git a/stable_pretraining/forward.py b/stable_pretraining/forward.py index f33f09241..baaa419a4 100644 --- a/stable_pretraining/forward.py +++ b/stable_pretraining/forward.py @@ -8,6 +8,7 @@ - ``supervised`` — standard supervised training - ``simclr`` — SimCLR contrastive learning - ``byol`` — BYOL momentum self-distillation + - ``resa`` — ReSA contrastive learning with Sinkhorn self-assignment - ``vicreg`` — VICReg variance-invariance-covariance regularization - ``barlow_twins`` — Barlow Twins cross-correlation alignment - ``swav`` — SwAV online clustering @@ -377,6 +378,121 @@ def byol(self, batch: dict[str, Any], stage: str) -> dict[str, torch.Tensor]: return out +def resa(self, batch: dict[str, Any], stage: str) -> dict[str, torch.Tensor]: + """Forward function for ReSA (Representation Self-Assignment). + + ReSA trains the student to predict soft targets built from its own + similarity structure. Sinkhorn-Knopp balances the cosine similarities + between the student's and the teacher's backbone features of the first + view, and each student projection is compared with the teacher projections + of the other views (see :class:`~stable_pretraining.losses.ReSALoss`). + + Args: + self: Module instance (automatically bound) with required attributes: + - backbone: TeacherStudentWrapper for feature extraction + - projector: TeacherStudentWrapper for the projection head + - resa_loss: ReSALoss instance + batch: Either a list of view dicts (from MultiViewTransform) or a single + dict (for validation/single-view). The first view is the assignment + view (weakly augmented in the paper); the teacher sees the first two + views. + stage: Training stage ('train', 'val', or 'test') + + Returns: + Dictionary containing: + - 'embedding': Teacher backbone features (EMA target) + - 'loss': ReSA loss (during training only) + - 'resa_assignment': Detached soft targets, for monitoring callbacks + (during training only) + - 'label': Labels if present (for probes/callbacks) + + Note: + Introduced in the ReSA paper :cite:`weng2025clustering`. + + Example: + :: + + import torch + import stable_pretraining as spt + from stable_pretraining.forward import resa + + backbone = spt.TeacherStudentWrapper( + spt.backbone.from_torchvision("resnet18", low_resolution=True) + ) + projector = spt.TeacherStudentWrapper(torch.nn.Linear(512, 512)) + module = spt.Module( + forward=resa, + backbone=backbone, + projector=projector, + resa_loss=spt.losses.ReSALoss(), + optim={"optimizer": {"type": "SGD", "lr": 0.3, "momentum": 0.9}}, + ) + """ + out = {} + + views = _get_views_list(batch) + if views is not None: + if len(views) < 2: + raise ValueError( + f"ReSA requires at least 2 views (the assignment view first), " + f"got {len(views)}." + ) + images = [view["image"] for view in views] + + if not self.training: + if "label" in views[0]: + out["label"] = torch.cat([view["label"] for view in views], dim=0) + with torch.no_grad(): + features = [self.backbone.forward_teacher(img) for img in images] + out["embedding"] = torch.cat(features, dim=0).detach() + return out + + if not hasattr(self, "resa_loss"): + raise ValueError( + "resa requires 'resa_loss' to be provided (e.g., spt.losses.ReSALoss()). " + "Pass it when constructing the Module: " + "Module(..., resa_loss=spt.losses.ReSALoss(), ...)" + ) + + # One backbone call per view keeps BatchNorm statistics per view. + student_features = [self.backbone.forward_student(img) for img in images] + student_proj = [self.projector.forward_student(f) for f in student_features] + with torch.no_grad(): + teacher_features = [ + self.backbone.forward_teacher(img) for img in images[:2] + ] + teacher_proj = [self.projector.forward_teacher(f) for f in teacher_features] + + assignment = self.resa_loss.assignment(student_features[0], teacher_features[0]) + out["loss"] = self.resa_loss( + student_features[0], + teacher_features[0], + student_proj, + teacher_proj, + assignment=assignment, + ) + out["resa_assignment"] = assignment + out["embedding"] = torch.cat(teacher_features, dim=0).detach() + if "label" in views[0]: + out["label"] = torch.cat([view["label"] for view in views[:2]], dim=0) + self.log( + f"{stage}/loss", + out["loss"], + on_step=True, + on_epoch=True, + sync_dist=True, + prog_bar=True, + ) + else: + # Single-view validation + if "label" in batch: + out["label"] = batch["label"] + with torch.no_grad(): + out["embedding"] = self.backbone.forward_teacher(batch["image"]).detach() + + return out + + def vicreg(self, batch: dict[str, Any], stage: str) -> dict[str, torch.Tensor]: """Forward function for VICReg (Variance-Invariance-Covariance Regularization). diff --git a/stable_pretraining/losses/__init__.py b/stable_pretraining/losses/__init__.py index 37eff8da9..dd954adb5 100644 --- a/stable_pretraining/losses/__init__.py +++ b/stable_pretraining/losses/__init__.py @@ -2,7 +2,7 @@ This module provides various self-supervised learning loss functions organized by category: - DINO losses: Self-distillation methods (DINOLoss, iBOTPatchLoss) -- Joint embedding losses: Contrastive and non-contrastive methods (BYOL, VICReg, Barlow Twins, SimCLR) +- Joint embedding losses: Contrastive and non-contrastive methods (BYOL, VICReg, Barlow Twins, SimCLR, ReSA) - Reconstruction losses: Masked prediction methods (MAE) - Utilities: Helper functions (sinkhorn_knopp, off_diagonal, NegativeCosineSimilarity) """ @@ -19,6 +19,9 @@ SwAVLoss, ) +# Representation Self-Assignment loss +from .resa import ReSALoss + # Multimodal losses from .multimodal import CLIPLoss @@ -44,6 +47,8 @@ "BarlowTwinsLoss", "NTXEntLoss", "SwAVLoss", + # ReSA + "ReSALoss", "CLIPLoss", # Reconstruction "mae", diff --git a/stable_pretraining/losses/resa.py b/stable_pretraining/losses/resa.py new file mode 100644 index 000000000..d8a931244 --- /dev/null +++ b/stable_pretraining/losses/resa.py @@ -0,0 +1,155 @@ +"""ReSA loss. + +Contrastive learning with Sinkhorn self-assignment targets. + +Reference: + Weng et al. "Clustering Properties of Self-Supervised Learning." ICML 2025. + https://arxiv.org/abs/2501.18452 + Official code: https://github.com/winci-ai/resa (ImageNet) and + https://github.com/winci-ai/resa_cifar (CIFAR). +""" + +from typing import Optional, Sequence + +import torch +import torch.nn.functional as F + +from ..utils import all_gather, get_world_size +from .utils import sinkhorn_knopp + + +class ReSALoss(torch.nn.Module): + """Representation Self-Assignment (ReSA) loss. + + This loss computes the cross-entropy between student and teacher + projections, using a self-assignment matrix as soft targets. The + self-assignment matrix is computed with the Sinkhorn-Knopp algorithm on + the cosine similarities between the student and teacher embeddings of one + view (the weakly augmented view in the paper). The student projection of + each view is compared with the teacher projections of every other view. + With an identity assignment the loss reduces to InfoNCE. + + Introduced in :cite:`weng2025clustering`. + + Args: + temperature: Temperature of the prediction softmax. Default is 0.4. + sinkhorn_temperature: Temperature of the Sinkhorn-Knopp assignment; + lower values give sharper targets. Default is 0.05. + sinkhorn_iterations: Number of Sinkhorn-Knopp iterations. Default is 3. + + Note: + Under DDP, the teacher embeddings and projections are gathered from + all ranks, so each rank's targets and predictions span the global + batch, while the student side stays local and DDP's gradient averaging + gives the global mean. Every rank must use the same local batch size. + + The loss is computed in float32 with autocast disabled. + """ + + def __init__( + self, + temperature: float = 0.4, + sinkhorn_temperature: float = 0.05, + sinkhorn_iterations: int = 3, + ): + super().__init__() + self.temperature = temperature + self.sinkhorn_temperature = sinkhorn_temperature + self.sinkhorn_iterations = sinkhorn_iterations + + @torch.no_grad() + def assignment( + self, student_embedding: torch.Tensor, teacher_embedding: torch.Tensor + ) -> torch.Tensor: + """Compute the Sinkhorn self-assignment targets. + + Args: + student_embedding: Student encoder features of the assignment view, + of shape ``[N, D]``. + teacher_embedding: Teacher encoder features of the same view, of + shape ``[N, D]``. + + Returns: + torch.Tensor: Float32 soft targets of shape ``[N, N * world_size]``. + Each row sums to 1. + """ + if student_embedding.shape != teacher_embedding.shape: + raise ValueError( + "student_embedding and teacher_embedding must have the same shape, got " + f"{tuple(student_embedding.shape)} and {tuple(teacher_embedding.shape)}." + ) + # exp(S / sinkhorn_temperature) amplifies rounding error, so stay in float32. + with torch.amp.autocast( + device_type=student_embedding.device.type, enabled=False + ): + student = F.normalize(student_embedding.float(), dim=1) + teacher = F.normalize( + torch.cat(all_gather(teacher_embedding), dim=0).float(), dim=1 + ) + return sinkhorn_knopp( + student @ teacher.T, + teacher_temp=self.sinkhorn_temperature, + num_samples=student.shape[0] * get_world_size(), + n_iterations=self.sinkhorn_iterations, + ) + + def forward( + self, + student_embedding: torch.Tensor, + teacher_embedding: torch.Tensor, + student_projections: Sequence[torch.Tensor], + teacher_projections: Sequence[torch.Tensor], + assignment: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + """Compute the ReSA loss. + + Args: + student_embedding: Student encoder features of the assignment view, + of shape ``[N, D]``. + teacher_embedding: Teacher encoder features of the same view, of + shape ``[N, D]``. + student_projections: Student projector outputs, one ``[N, d]`` + tensor per view. View ``i`` is compared with every teacher + view ``j != i``. + teacher_projections: Teacher projector outputs, one ``[N, d]`` + tensor per view, in the same view order as + ``student_projections``. Usually only the first two views. + assignment: Targets precomputed with :meth:`assignment`, for + example to log diagnostics without running Sinkhorn twice. + Computed from the embeddings when omitted. + + Returns: + torch.Tensor: Scalar loss, the mean soft-target cross-entropy over + every (student view, teacher view) pair of different views. + """ + pairs = [ + (i, j) + for i in range(len(student_projections)) + for j in range(len(teacher_projections)) + if i != j + ] + if not pairs: + raise ValueError( + "ReSALoss needs at least one student view and one different teacher " + f"view, got {len(student_projections)} student and " + f"{len(teacher_projections)} teacher projection(s)." + ) + if assignment is None: + assignment = self.assignment(student_embedding, teacher_embedding) + + with torch.amp.autocast( + device_type=student_embedding.device.type, enabled=False + ): + with torch.no_grad(): + targets = [ + F.normalize(torch.cat(all_gather(t), dim=0).float(), dim=1) + for t in teacher_projections + ] + predictions = [F.normalize(z.float(), dim=1) for z in student_projections] + losses = [ + F.cross_entropy( + predictions[i] @ targets[j].T / self.temperature, assignment + ) + for i, j in pairs + ] + return torch.stack(losses).mean() diff --git a/stable_pretraining/methods/__init__.py b/stable_pretraining/methods/__init__.py index 7cc3209bb..b05641d6e 100644 --- a/stable_pretraining/methods/__init__.py +++ b/stable_pretraining/methods/__init__.py @@ -21,6 +21,7 @@ from .nnclr import NNCLR from .pirl import PIRL from .pmsn import PMSN +from .resa import ReSA from .salt import SALT from .simclr import SimCLR from .simmim import SimMIM @@ -56,6 +57,7 @@ "NNCLR", "PIRL", "PMSN", + "ReSA", "SALT", "SimCLR", "SimMIM", diff --git a/stable_pretraining/methods/resa.py b/stable_pretraining/methods/resa.py new file mode 100644 index 000000000..5cac506eb --- /dev/null +++ b/stable_pretraining/methods/resa.py @@ -0,0 +1,155 @@ +"""ReSA: Representation Self-Assignment. + +Contrastive learning whose targets come from the encoder's own similarity +structure. Sinkhorn-Knopp turns the cosine similarities between the student's +and the EMA teacher's encoder features of the first (weakly augmented) view +into soft labels, and each student projection learns to match them against the +teacher projection of the other view. + +References: + Weng et al. "Clustering Properties of Self-Supervised Learning." ICML 2025. + https://arxiv.org/abs/2501.18452 + +Example:: + + import lightning as pl + import stable_pretraining as spt + + model = spt.ReSA(encoder_name="resnet18", low_resolution=True) + + trainer = pl.Trainer(max_epochs=1000) + spt.Manager(trainer=trainer, module=model, data=data)() +""" + +from typing import Sequence, Union + +import torch +import torch.nn as nn + +from stable_pretraining import Module +from stable_pretraining.backbone import TeacherStudentWrapper, from_timm +from stable_pretraining.forward import resa +from stable_pretraining.losses import ReSALoss + + +def _build_resa_projector(in_dim: int, dims: Sequence[int]) -> nn.Module: + """ReSA projector: Linear -> BN -> ReLU -> ... -> Linear -> BN(affine=False). + + :param in_dim: Backbone output dimension + :param dims: Hidden + output dimensions, e.g. (2048, 2048, 512) + """ + if len(dims) < 1: + raise ValueError( + "projector_dims must contain at least one entry (the output dim)" + ) + layers = [] + prev = in_dim + for i, dim in enumerate(dims): + layers.append(nn.Linear(prev, dim)) + if i == len(dims) - 1: + layers.append(nn.BatchNorm1d(dim, affine=False)) + else: + layers.append(nn.BatchNorm1d(dim)) + layers.append(nn.ReLU(inplace=True)) + prev = dim + return nn.Sequential(*layers) + + +class ReSA(Module): + """ReSA self-supervised learning with an EMA teacher and Sinkhorn soft labels. + + The forward is :func:`~stable_pretraining.forward.resa`: it takes the batch + dict and the stage, as :class:`~stable_pretraining.Module` calls it in its + training and evaluation steps, and returns a dict. + + Architecture: + - **Backbone**: any feature extractor producing a flat [B, D] embedding, + wrapped with an EMA teacher + - **Projector**: MLP ending in a BatchNorm without affine parameters, + also wrapped with an EMA teacher + - **Loss**: :class:`~stable_pretraining.losses.ReSALoss` + + :param encoder_name: timm model name (e.g. ``"resnet18"``, + ``"vit_small_patch16_224"``) or a pre-instantiated ``nn.Module`` whose + ``forward`` returns a ``[B, D]`` tensor. + :param projector_dims: Hidden + output dimensions of the projector. + ``(2048, 2048, 512)`` matches the official CIFAR recipe. + :param temperature: Temperature of the cross-view predictions (0.4 in the + paper). + :param sinkhorn_temperature: Temperature of the similarities that build the + soft labels (0.05 in the paper). + :param sinkhorn_iterations: Sinkhorn-Knopp normalization rounds (3 in the + paper). + :param ema_decay_start: Initial teacher EMA decay (0.996 in the paper). + :param ema_decay_end: Final teacher EMA decay (1.0). + :param low_resolution: Adapt the first conv for 32x32 inputs (CIFAR-style). + :param pretrained: Load pretrained timm weights for the encoder. + + Note: + Put the weakly augmented view (crop and flip only) first in + ``batch["views"]``: the soft labels are built from it. Use + :class:`~stable_pretraining.callbacks.TeacherStudentCallback` to drive + the teacher EMA updates during training. It updates the teacher every + step but recomputes the momentum once per epoch, so the momentum lags + the official code's per-iteration schedule by at most one epoch. + + Example:: + + model = ReSA(encoder_name="resnet18", low_resolution=True) + + weak = {"image": torch.randn(256, 3, 32, 32)} + strong = {"image": torch.randn(256, 3, 32, 32)} + out = model({"views": [weak, strong]}, stage="fit") + out["loss"].backward() + + # eval: single view, no loss + model.eval() + out = model(weak, stage="validate") + features = out["embedding"] # [256, embed_dim], from the teacher + """ + + def __init__( + self, + encoder_name: Union[str, nn.Module] = "resnet18", + projector_dims: Sequence[int] = (2048, 2048, 512), + temperature: float = 0.4, + sinkhorn_temperature: float = 0.05, + sinkhorn_iterations: int = 3, + ema_decay_start: float = 0.996, + ema_decay_end: float = 1.0, + low_resolution: bool = False, + pretrained: bool = False, + ): + super().__init__(forward=resa) + + if isinstance(encoder_name, str): + base_backbone = from_timm( + encoder_name, + num_classes=0, + low_resolution=low_resolution, + pretrained=pretrained, + ) + else: + base_backbone = encoder_name + + with torch.no_grad(): + embed_dim = base_backbone(torch.zeros(1, 3, 224, 224)).shape[-1] + self.embed_dim = embed_dim + + self.backbone = TeacherStudentWrapper( + base_backbone, + warm_init=True, + base_ema_coefficient=ema_decay_start, + final_ema_coefficient=ema_decay_end, + ) + self.projector = TeacherStudentWrapper( + _build_resa_projector(embed_dim, list(projector_dims)), + warm_init=True, + base_ema_coefficient=ema_decay_start, + final_ema_coefficient=ema_decay_end, + ) + self.resa_loss = ReSALoss( + temperature=temperature, + sinkhorn_temperature=sinkhorn_temperature, + sinkhorn_iterations=sinkhorn_iterations, + ) diff --git a/stable_pretraining/tests/regression/_capture_refs.py b/stable_pretraining/tests/regression/_capture_refs.py index 6b8401f20..cf18e85da 100644 --- a/stable_pretraining/tests/regression/_capture_refs.py +++ b/stable_pretraining/tests/regression/_capture_refs.py @@ -102,6 +102,16 @@ def make_data(multi_view=True): ), data=make_data(True), ), + "resa": lambda: dict( + module=spt.Module( + backbone=spt.backbone.TeacherStudentWrapper(make_backbone()), + projector=spt.backbone.TeacherStudentWrapper(make_projector()), + forward=forward.resa, + resa_loss=losses.ReSALoss(), + optim={"optimizer": {"type": "Adam", "lr": 1e-3}}, + ), + data=make_data(True), + ), "vicreg": lambda: dict( module=spt.Module( backbone=make_backbone(), diff --git a/stable_pretraining/tests/regression/test_methods.py b/stable_pretraining/tests/regression/test_methods.py index e7a3f9915..212a6bb68 100644 --- a/stable_pretraining/tests/regression/test_methods.py +++ b/stable_pretraining/tests/regression/test_methods.py @@ -171,6 +171,19 @@ def build_byol(): ) +def build_resa(): + return dict( + module=spt.Module( + backbone=spt.backbone.TeacherStudentWrapper(make_backbone()), + projector=spt.backbone.TeacherStudentWrapper(make_projector()), + forward=forward.resa, + resa_loss=losses.ReSALoss(), + optim={"optimizer": {"type": "Adam", "lr": 1e-3}}, + ), + data=make_data(multi_view=True), + ) + + def build_vicreg(): return dict( module=spt.Module( @@ -217,6 +230,7 @@ def build_supervised(): METHOD_BUILDERS = { "simclr": build_simclr, "byol": build_byol, + "resa": build_resa, "vicreg": build_vicreg, "barlow_twins": build_barlow_twins, "supervised": build_supervised, @@ -228,6 +242,7 @@ def build_supervised(): REFERENCE_LOSSES = { "simclr": ("fit/loss_epoch", 1.645321011543274), "byol": ("fit/loss_epoch", 1.822302222251892), + "resa": ("fit/loss_epoch", 2.295149326324463), # captured on 2026-10-21 "vicreg": ("fit/loss_epoch", 18.119741439819336), "barlow_twins": ("fit/loss_epoch", 1.7105509042739868), "supervised": ("validate/loss_step", 2.3338754177093506), diff --git a/stable_pretraining/tests/regression/test_resa_resume.py b/stable_pretraining/tests/regression/test_resa_resume.py new file mode 100644 index 000000000..10f65d81f --- /dev/null +++ b/stable_pretraining/tests/regression/test_resa_resume.py @@ -0,0 +1,124 @@ +"""ReSA restarted from a full checkpoint matches uninterrupted training.""" + +import lightning as pl +import pytest +import torch +from torch import nn +from torch.utils.data import DataLoader + +import stable_pretraining as spt + +from ._interaction_helpers import _assert_tree_close + +pytestmark = [pytest.mark.regression, pytest.mark.usefixtures("interaction_runtime")] + +STEPS_PER_EPOCH = 4 + + +class _StopAfterEpoch(pl.Callback): + """Keep the planned training horizon unchanged while stopping the first leg.""" + + def on_train_epoch_end(self, trainer, pl_module): + trainer.should_stop = True + + +def _module(): + with torch.random.fork_rng(devices=[]): + torch.manual_seed(31) + encoder = nn.Sequential( + nn.Conv2d(3, 8, 3, padding=1), + nn.BatchNorm2d(8), + nn.ReLU(), + nn.AdaptiveAvgPool2d(1), + nn.Flatten(), + ) + module = spt.ReSA( + encoder_name=encoder, projector_dims=(16, 8), ema_decay_start=0.9 + ) + module.optim = { + "optimizer": { + "type": "SGD", + "lr": 0.1, + "momentum": 0.9, + "weight_decay": 1e-4, + }, + "scheduler": { + "type": "LinearWarmupCosineAnnealingLR", + "warmup_steps": 2, + "max_steps": 3 * STEPS_PER_EPOCH, + "warmup_start_lr": 0.0, + "eta_min": 0.01, + }, + "interval": "step", + } + return module + + +def _data(): + g = torch.Generator().manual_seed(17) + images = torch.randn(16, 3, 8, 8, generator=g) + noise = 0.1 * torch.randn(2, 16, 3, 8, 8, generator=g) + train = [ + { + "views": [ + {"image": images[i] + noise[v, i], "label": torch.tensor(i % 2)} + for v in range(2) + ] + } + for i in range(16) + ] + val = [{"image": images[i], "label": torch.tensor(i % 2)} for i in range(8)] + return spt.data.DataModule( + train=DataLoader(train, batch_size=4, shuffle=False), + val=DataLoader(val, batch_size=4, shuffle=False), + ) + + +def _train(module, callbacks=(), ckpt_path=None): + trainer = pl.Trainer( + accelerator="cpu", + devices=1, + precision="32-true", + max_epochs=3, + logger=False, + enable_checkpointing=False, + enable_progress_bar=False, + enable_model_summary=False, + num_sanity_val_steps=0, + callbacks=list(callbacks), + ) + spt.Manager( + trainer=trainer, + module=module, + data=_data(), + seed=59, + ckpt_path=ckpt_path, + weights_only=False, + )() + return trainer + + +def test_resa_restart_matches_uninterrupted_training(tmp_path): + reference = _module() + full = _train(reference) + + interrupted = _module() + first = _train(interrupted, callbacks=[_StopAfterEpoch()]) + assert first.global_step == STEPS_PER_EPOCH + checkpoint = tmp_path / "resa.ckpt" + first.save_checkpoint(checkpoint) + + resumed = _module() + with torch.no_grad(): + for parameter in resumed.parameters(): + parameter.add_(10) + second = _train(resumed, ckpt_path=str(checkpoint)) + + assert second.global_step == full.global_step == 3 * STEPS_PER_EPOCH + # Student and teacher weights, BatchNorm statistics and the EMA + # coefficient buffers all follow the uninterrupted run. + _assert_tree_close(resumed.state_dict(), reference.state_dict()) + assert resumed.backbone.ema_coefficient.item() < 1.0 + assert not torch.equal( + resumed.backbone.teacher[0].weight, resumed.backbone.student[0].weight + ) diff --git a/stable_pretraining/tests/unit/licenses/RESA_CIFAR_LICENSE b/stable_pretraining/tests/unit/licenses/RESA_CIFAR_LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/stable_pretraining/tests/unit/licenses/RESA_CIFAR_LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/stable_pretraining/tests/unit/test_forward_functions.py b/stable_pretraining/tests/unit/test_forward_functions.py index 78452ee7c..6c4edae43 100644 --- a/stable_pretraining/tests/unit/test_forward_functions.py +++ b/stable_pretraining/tests/unit/test_forward_functions.py @@ -182,6 +182,31 @@ def test_byol_forward_with_benchmark_transforms(self): assert "embedding" in result assert "loss" in result + def test_resa_forward_with_benchmark_transforms(self): + """Test resa with SimCLR-style transforms (2 views) and the real loss.""" + sample = {"image": _create_dummy_pil_image(), "label": torch.tensor([0])} + + transform = _simclr_transforms() + batch = transform(sample) + + # Create module with teacher-student wrappers + module = Mock() + module.backbone = Mock() + module.backbone.forward_student = lambda x: torch.randn(x.shape[0], 512) + module.backbone.forward_teacher = lambda x: torch.randn(x.shape[0], 512) + module.projector = Mock() + module.projector.forward_student = lambda x: torch.randn(x.shape[0], 128) + module.projector.forward_teacher = lambda x: torch.randn(x.shape[0], 128) + module.resa_loss = spt.losses.ReSALoss() + module.training = True + module.log = Mock() + + result = forward_module.resa(module, batch, "train") + + assert "embedding" in result + assert torch.isfinite(result["loss"]) + assert "resa_assignment" in result + def test_vicreg_forward_with_benchmark_transforms(self): """Test vicreg with benchmark transforms.""" sample = {"image": _create_dummy_pil_image()} diff --git a/stable_pretraining/tests/unit/test_method_boundary_contracts.py b/stable_pretraining/tests/unit/test_method_boundary_contracts.py index 3634f7d2a..31ea02792 100644 --- a/stable_pretraining/tests/unit/test_method_boundary_contracts.py +++ b/stable_pretraining/tests/unit/test_method_boundary_contracts.py @@ -47,6 +47,7 @@ def test_joint_embedding_methods_accept_existing_encoder_for_evaluation(name): ("simclr", "_build_projector"), ("barlow_twins", "_build_barlow_projector"), ("vicreg", "_build_vicreg_projector"), + ("resa", "_build_resa_projector"), ], ) def test_projector_requires_an_output_dimension(name, fn): diff --git a/stable_pretraining/tests/unit/test_module_and_forward_edges.py b/stable_pretraining/tests/unit/test_module_and_forward_edges.py index 4e61af6fb..d02ff2481 100644 --- a/stable_pretraining/tests/unit/test_module_and_forward_edges.py +++ b/stable_pretraining/tests/unit/test_module_and_forward_edges.py @@ -13,11 +13,13 @@ pytestmark = pytest.mark.unit -@pytest.mark.parametrize("name", ["byol", "vicreg", "barlow_twins", "swav", "nnclr"]) +@pytest.mark.parametrize( + "name", ["byol", "vicreg", "barlow_twins", "swav", "nnclr", "resa"] +) @pytest.mark.parametrize("multiple", [False, True]) def test_ssl_evaluation_preserves_labels_and_does_not_require_loss(name, multiple): backbone = nn.Linear(3, 4) - wrapped = TeacherStudentWrapper(backbone) if name == "byol" else backbone + wrapped = TeacherStudentWrapper(backbone) if name in ("byol", "resa") else backbone model = SimpleNamespace(backbone=wrapped, training=False) views = [ {"image": torch.randn(2, 3), "label": torch.tensor([0, 1])} for _ in range(2) diff --git a/stable_pretraining/tests/unit/test_resa.py b/stable_pretraining/tests/unit/test_resa.py new file mode 100644 index 000000000..4bcf4faf2 --- /dev/null +++ b/stable_pretraining/tests/unit/test_resa.py @@ -0,0 +1,342 @@ +"""Unit tests for ReSA: the loss, the forward function and the method class. + +The reference loss below is the official ReSA CIFAR implementation +(https://github.com/winci-ai/resa_cifar, method/base.py and method/resa.py), +reduced to a single process. Copyright (c) Winci, licensed under the Apache +License, Version 2.0. +""" + +from unittest.mock import Mock + +import pytest +import torch +import torch.distributed as dist +import torch.nn.functional as F +from timm.models.vision_transformer import VisionTransformer + +from stable_pretraining.forward import resa +from stable_pretraining.losses import ReSALoss +from stable_pretraining.losses.joint_embedding import InfoNCELoss +from stable_pretraining.methods import ReSA + + +@torch.no_grad() +def _official_sinkhorn_knopp(scores, temp=0.05, n_iterations=3): + q = torch.exp(scores / temp).t() + num_samples, num_prototypes = q.shape[1], q.shape[0] + q /= q.sum() + for _ in range(n_iterations): + q /= q.sum(dim=1, keepdim=True) + q /= num_prototypes + q /= q.sum(dim=0, keepdim=True) + q /= num_samples + q *= num_samples + return q.t() + + +def _official_loss(h_student, z_student, h_teacher, z_teacher, temp=0.4): + h = F.normalize(h_student).detach() + emb = [F.normalize(z) for z in z_student] + with torch.no_grad(): + h_m = F.normalize(h_teacher) + emb_m = [F.normalize(z) for z in z_teacher[:2]] + assign = _official_sinkhorn_knopp(h @ h_m.T) + losses = [ + -(assign * F.log_softmax(emb[q] @ emb_m[v].T / temp, dim=1)).sum(dim=1).mean() + for q in range(len(emb)) + for v in range(len(emb_m)) + if v != q + ] + return sum(losses) / len(losses) + + +def _embeddings(n=64, views=2, scale=1.0, seed=0): + """Backbone features (student and a nearby teacher) and projections.""" + g = torch.Generator().manual_seed(seed) + h_s = torch.randn(n, 512, generator=g) * scale + h_t = h_s + 0.3 * scale * torch.randn(n, 512, generator=g) + z_s = [torch.randn(n, 128, generator=g).requires_grad_() for _ in range(views)] + z_t = [torch.randn(n, 128, generator=g) for _ in range(2)] + return h_s, h_t, z_s, z_t + + +@pytest.mark.unit +class TestReSALoss: + """ReSALoss against the official implementation, plus edge cases.""" + + @pytest.mark.parametrize("views", [2, 4]) + def test_matches_official_loss_and_gradients(self, views): + h_s, h_t, z_s, z_t = _embeddings(views=views) + loss = ReSALoss()(h_s, h_t, z_s, z_t) + grads = torch.autograd.grad(loss, z_s) + + z_ref = [z.detach().clone().requires_grad_() for z in z_s] + ref = _official_loss(h_s, z_ref, h_t, z_t) + ref_grads = torch.autograd.grad(ref, z_ref) + + torch.testing.assert_close(loss, ref, rtol=0, atol=1e-5) + for grad, ref_grad in zip(grads, ref_grads): + torch.testing.assert_close(grad, ref_grad, rtol=0, atol=1e-6) + + def test_identity_assignment_reduces_to_infonce(self): + h_s, h_t, z_s, z_t = _embeddings() + n = h_s.shape[0] + loss = ReSALoss()(h_s, h_t, z_s, z_t, assignment=torch.eye(n)) + + infonce = InfoNCELoss(temperature=0.4) + targets = torch.arange(n) + ref = 0.5 * ( + infonce(z_s[0], z_t[1], targets) + infonce(z_s[1], z_t[0], targets) + ) + torch.testing.assert_close(loss, ref, rtol=0, atol=1e-5) + + def test_assignment_is_a_float32_soft_label_matrix(self): + h_s, h_t, _, _ = _embeddings() + assignment = ReSALoss().assignment(h_s, h_t) + + assert assignment.shape == (64, 64) + assert assignment.dtype == torch.float32 + assert not assignment.requires_grad + assert (assignment >= 0).all() + torch.testing.assert_close( + assignment.sum(dim=1), torch.ones(64), rtol=0, atol=1e-5 + ) + + def test_gradients_reach_only_student_projections(self): + h_s, h_t, z_s, z_t = _embeddings() + h_s.requires_grad_() + h_t.requires_grad_() + for z in z_t: + z.requires_grad_() + + ReSALoss()(h_s, h_t, z_s, z_t).backward() + + assert all(z.grad is not None and z.grad.abs().sum() > 0 for z in z_s) + assert h_s.grad is None and h_t.grad is None + assert all(z.grad is None for z in z_t) + + def test_bf16_autocast_computes_in_float32(self): + h_s, h_t, z_s, z_t = ( + [x.detach().to(torch.bfloat16) for x in xs] + if isinstance(xs, list) + else xs.to(torch.bfloat16) + for xs in _embeddings() + ) + with torch.autocast(device_type="cpu", dtype=torch.bfloat16): + loss = ReSALoss()(h_s, h_t, z_s, z_t) + + ref = _official_loss( + h_s.float(), [z.float() for z in z_s], h_t.float(), [z.float() for z in z_t] + ) + assert loss.dtype == torch.float32 + torch.testing.assert_close(loss, ref, rtol=0, atol=1e-5) + + def test_collapsed_batch_stays_finite(self): + h_s, _, z_s, z_t = _embeddings() + h_s = h_s[:1].expand_as(h_s).clone() + z_s = [z[:1].detach().expand_as(z).clone().requires_grad_() for z in z_s] + z_t = [z[:1].expand_as(z).clone() for z in z_t] + + loss = ReSALoss()(h_s, h_s.clone(), z_s, z_t) + loss.backward() + + assert torch.isfinite(loss) + assert all(torch.isfinite(z.grad).all() for z in z_s) + + def test_huge_features_stay_finite(self): + h_s, h_t, z_s, z_t = _embeddings(scale=1e4) + loss = ReSALoss()(h_s, h_t, z_s, z_t) + loss.backward() + + assert torch.isfinite(loss) + assert all(torch.isfinite(z.grad).all() for z in z_s) + + def test_raises_on_mismatched_embeddings(self): + h_s, h_t, z_s, z_t = _embeddings() + with pytest.raises(ValueError, match="same shape"): + ReSALoss()(h_s, h_t[:10], z_s, z_t) + + def test_raises_without_a_cross_view_pair(self): + h_s, h_t, z_s, z_t = _embeddings() + with pytest.raises(ValueError, match="at least one student view"): + ReSALoss()(h_s, h_t, z_s[:1], z_t[:1]) + + +def _two_rank_resa(rank, rendezvous): + from datetime import timedelta + + torch.set_num_threads(1) + dist.init_process_group( + "gloo", + init_method=rendezvous, + rank=rank, + world_size=2, + timeout=timedelta(seconds=45), + ) + try: + # Every rank builds the same full batch, keeps its half, and compares + # with the single-process reference on the whole batch. + h_s, h_t, z_s, z_t = _embeddings(n=16) + z_ref = [z.detach().clone().requires_grad_() for z in z_s] + ref = _official_loss(h_s, z_ref, h_t, z_t) + ref.backward() + ref_assignment = _official_sinkhorn_knopp(F.normalize(h_s) @ F.normalize(h_t).T) + + rows = slice(rank * 8, (rank + 1) * 8) + loss_fn = ReSALoss() + local_z_s = [z[rows].detach().clone().requires_grad_() for z in z_s] + assignment = loss_fn.assignment(h_s[rows], h_t[rows]) + loss = loss_fn( + h_s[rows], + h_t[rows], + local_z_s, + [z[rows] for z in z_t], + assignment=assignment, + ) + + # Sinkhorn sums over the global batch, so each rank's soft labels are + # its rows of the full-batch soft labels. + torch.testing.assert_close( + assignment, ref_assignment[rows], rtol=1e-4, atol=1e-6 + ) + mean_loss = loss.detach().clone() + dist.all_reduce(mean_loss) + torch.testing.assert_close(mean_loss / 2, ref.detach(), rtol=0, atol=1e-5) + # Each rank averages over half the rows, so its gradients are twice the + # full-batch ones; DDP's averaging across the two ranks restores them. + loss.backward() + for local, full in zip(local_z_s, z_ref): + torch.testing.assert_close( + local.grad / 2, full.grad[rows], rtol=1e-4, atol=1e-6 + ) + finally: + dist.destroy_process_group() + + +@pytest.mark.unit +@pytest.mark.skipif(not dist.is_gloo_available(), reason="Gloo unavailable") +def test_two_rank_loss_matches_full_batch(tmp_path): + torch.multiprocessing.spawn( + _two_rank_resa, + args=((tmp_path / "two-rank-rendezvous").as_uri(),), + nprocs=2, + join=True, + ) + + +def _module(training=True): + """A module with mocked teacher-student wrappers and the real ReSA loss.""" + module = Mock() + module.training = training + module.backbone.forward_student = Mock( + side_effect=lambda x: torch.randn(x.shape[0], 512, requires_grad=True) + ) + module.backbone.forward_teacher = Mock( + side_effect=lambda x: torch.randn(x.shape[0], 512) + ) + module.projector.forward_student = Mock( + side_effect=lambda x: torch.randn(x.shape[0], 128, requires_grad=True) + ) + module.projector.forward_teacher = Mock( + side_effect=lambda x: torch.randn(x.shape[0], 128) + ) + module.resa_loss = ReSALoss() + module.log = Mock() + return module + + +def _views(n_views, n=8): + return { + "views": [ + {"image": torch.randn(n, 3, 32, 32), "label": torch.arange(n)} + for _ in range(n_views) + ] + } + + +@pytest.mark.unit +class TestReSAForward: + """The resa forward function with mocked teacher-student wrappers.""" + + def test_training_returns_loss_embedding_and_assignment(self): + module = _module() + out = resa(module, _views(2), "train") + + assert out["loss"].ndim == 0 and torch.isfinite(out["loss"]) + assert out["embedding"].shape == (16, 512) + assert not out["embedding"].requires_grad + assert out["resa_assignment"].shape == (8, 8) + assert out["label"].shape == (16,) + module.log.assert_called_once() + + def test_teacher_sees_only_the_first_two_views(self): + module = _module() + out = resa(module, _views(4), "train") + + assert module.backbone.forward_student.call_count == 4 + assert module.backbone.forward_teacher.call_count == 2 + assert out["embedding"].shape == (16, 512) + + def test_eval_returns_teacher_embedding_without_loss(self): + module = _module(training=False) + batch = {"image": torch.randn(8, 3, 32, 32), "label": torch.arange(8)} + out = resa(module, batch, "val") + + assert "loss" not in out + assert out["embedding"].shape == (8, 512) + module.backbone.forward_student.assert_not_called() + + def test_raises_with_a_single_view(self): + with pytest.raises(ValueError, match="at least 2 views"): + resa(_module(), _views(1), "train") + + def test_raises_without_resa_loss(self): + module = _module() + del module.resa_loss + with pytest.raises(ValueError, match="resa_loss"): + resa(module, _views(2), "train") + + +@pytest.mark.unit +class TestReSAMethod: + """The ReSA class runs the resa forward function on Module batches.""" + + def test_fit_batch_trains_the_student(self): + model = ReSA(encoder_name="vit_tiny_patch16_224", projector_dims=(256, 256, 64)) + model.log = Mock() + views = [ + {"image": torch.randn(2, 3, 224, 224), "label": torch.arange(2)} + for _ in range(2) + ] + out = model({"views": views, "batch_idx": 0}, stage="fit") + + assert set(out) == {"loss", "embedding", "resa_assignment", "label"} + assert out["loss"].ndim == 0 and torch.isfinite(out["loss"]) + assert out["embedding"].shape == (4, 192) + out["loss"].backward() + assert any( + p.grad is not None and p.grad.abs().sum() > 0 + for p in model.backbone.student.parameters() + ) + assert all(p.grad is None for p in model.backbone.teacher.parameters()) + + def test_validate_batch_returns_teacher_embedding_without_loss(self): + encoder = VisionTransformer( + img_size=32, + patch_size=8, + embed_dim=24, + depth=2, + num_heads=3, + num_classes=0, + dynamic_img_size=True, + ) + model = ReSA(encoder_name=encoder, projector_dims=(16, 8)).eval() + model.log = Mock() + images = torch.randn(2, 3, 32, 32) + with torch.no_grad(): + out = model({"image": images, "label": torch.arange(2)}, stage="validate") + teacher = model.backbone.forward_teacher(images) + + assert set(out) == {"embedding", "label"} + torch.testing.assert_close(out["embedding"], teacher) + model.log.assert_not_called()