diff --git a/METHODS.md b/METHODS.md index a8d123535..2f2735f19 100644 --- a/METHODS.md +++ b/METHODS.md @@ -43,6 +43,7 @@ Methods come in two forms: | PIRL | — | `PIRL` | — | — | [Misra & van der Maaten, 2020](https://arxiv.org/abs/1912.01991) | | PMSN | — | `PMSN` | — | — | [Assran et al., 2023](https://arxiv.org/abs/2210.07277) | | SALT | — | `SALT` | — | — | [Li et al., 2025](https://arxiv.org/pdf/2509.24317) | +| ReSSL | `ressl` | `ReSSL` | `ReSSLLoss` | `TeacherStudent†` | [Zheng et al., 2021](https://arxiv.org/abs/2107.09282) | | SimMIM | — | `SimMIM` | — | — | [Xie et al., 2022](https://arxiv.org/abs/2111.09886) | | SimSiam | — | `SimSiam` | — | — | [Chen & He, 2021](https://arxiv.org/abs/2011.10566) | | TiCO | — | `TiCO` | — | — | [Zhu et al., 2022](https://arxiv.org/abs/2206.10698) | @@ -112,5 +113,6 @@ All loss classes are importable from `stable_pretraining.losses`: | `DINOv2Loss` | DINOv2, DINOv3 | | `iBOTPatchLoss` | DINOv2, iBOT, MIMRefiner | | `MAELoss` | MAE | +| `ReSSLLoss` | ReSSL | | `CLIPLoss` | Multimodal CLIP-style objectives | | `NegativeCosineSimilarity` | SimSiam, general use | diff --git a/RELEASES.rst b/RELEASES.rst index 9b10a58e6..aa8a35883 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``. +- ``ReSSL`` (Relational Self-Supervised Learning): student-teacher self-supervised + learning that matches relational similarity distributions over a queue of + teacher embeddings using weak teacher and strong student augmentations. + Implements temperature-scaled relational cross-entropy, parameter-only EMA + teacher updates, SplitBatchNorm, and DDP-compatible queue synchronization, + per Zheng et al., "ReSSL: Relational Self-Supervised Learning with Weak + Augmentation" (NeurIPS 2021). Registered in ``stable_pretraining.methods`` + and ``METHODS.md``, with a CIFAR-10 ResNet-18 benchmark under + ``benchmarks/cifar10/ressl-resnet18.py``. **Discoverability improvements** diff --git a/benchmarks/cifar10/ressl-resnet18-lineareval.py b/benchmarks/cifar10/ressl-resnet18-lineareval.py new file mode 100644 index 000000000..7c423b06a --- /dev/null +++ b/benchmarks/cifar10/ressl-resnet18-lineareval.py @@ -0,0 +1,271 @@ +"""Linear evaluation of a frozen ReSSL CIFAR-10 backbone. + +Evaluate a frozen student or teacher backbone with a CIFAR-10 linear probe. + +Examples: + python benchmarks/cifar10/ressl-resnet18-lineareval.py \ + --checkpoint /path/to/last.ckpt + + python benchmarks/cifar10/ressl-resnet18-lineareval.py \ + --checkpoint /path/to/last.ckpt \ + --branch teacher +""" + +import argparse +import csv +import lightning as pl +import os +from pathlib import Path + +import stable_pretraining as spt +import torch +import torch.nn as nn +import torchvision +from torch.utils.data import DataLoader +from torchvision import transforms + + +def parse_args(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--checkpoint", + type=Path, + required=True, + help="Path to a pretrained ReSSL Lightning checkpoint.", + ) + parser.add_argument( + "--branch", + choices=("student", "teacher"), + default=os.environ.get("BRANCH", "student"), + ) + parser.add_argument("--output-dir", type=Path, default=None) + parser.add_argument( + "--data-dir", + type=Path, + default=None, + help="CIFAR-10 root containing cifar-10-batches-py.", + ) + parser.add_argument( + "--batch-size", type=int, default=int(os.environ.get("BATCH_SIZE", "256")) + ) + parser.add_argument( + "--epochs", type=int, default=int(os.environ.get("EPOCHS", "100")) + ) + parser.add_argument( + "--lr", + type=float, + default=float(os.environ["LR"]) if os.environ.get("LR") else None, + ) + parser.add_argument( + "--schedule", + choices=("cosine", "step"), + default=os.environ.get("SCHEDULE", "step"), + ) + parser.add_argument( + "--num-workers", type=int, default=int(os.environ.get("NUM_WORKERS", "4")) + ) + parser.add_argument("--seed", type=int, default=42) + return parser.parse_args() + + +def main(): + args = parse_args() + pl.seed_everything(args.seed, workers=True) + args.checkpoint = args.checkpoint.expanduser().resolve() + if args.lr is None: + args.lr = 0.2 if args.schedule == "cosine" else 30.0 + output_dir = ( + (args.output_dir or Path.home() / f"ressl-{args.branch}-eval-exact-augment") + .expanduser() + .resolve() + ) + + if not args.checkpoint.is_file(): + raise FileNotFoundError( + f"Checkpoint not found: {args.checkpoint}\n" + "Locate checkpoints with: find ~/.cache/stable-pretraining/runs -name '*.ckpt'" + ) + if not torch.cuda.is_available(): + raise RuntimeError("CUDA GPU required to run this evaluation.") + + device = torch.device("cuda") + output_dir.mkdir(parents=True, exist_ok=True) + + ckpt = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + print("Checkpoint epoch:", ckpt.get("epoch", "unknown"), flush=True) + print("Checkpoint global_step:", ckpt.get("global_step", "unknown"), flush=True) + weights = ckpt.get("state_dict", ckpt) + prefix = f"backbone.{args.branch}." + branch_weights = { + key[len(prefix) :]: value + for key, value in weights.items() + if key.startswith(prefix) + } + if not branch_weights: + raise RuntimeError( + f"No {prefix}* weights found. Inspect checkpoint state_dict keys." + ) + + backbone = spt.backbone.from_torchvision("resnet18", low_resolution=True) + backbone.fc = nn.Identity() + backbone.load_state_dict(branch_weights, strict=True) + backbone.requires_grad_(False) + backbone.to(device).eval() + print( + f"Loaded and froze {args.branch} backbone:", + len(branch_weights), + "state entries", + flush=True, + ) + + mean = (0.4914, 0.4822, 0.4465) + std = (0.2023, 0.1994, 0.2010) + normalize = transforms.Normalize(mean, std) + train_transform = transforms.Compose( + [ + transforms.RandomResizedCrop(32), + transforms.RandomHorizontalFlip(), + transforms.ToTensor(), + normalize, + ] + ) + test_transform = transforms.Compose([transforms.ToTensor(), normalize]) + + if args.data_dir is not None: + data_root = args.data_dir.expanduser() + elif os.environ.get("DATA_DIR"): + data_root = Path(os.environ["DATA_DIR"]).expanduser() + else: + base = Path( + os.environ.get( + "STABLE_PRETRAINING_DATA_DIR", + str(Path.home() / ".cache" / "stable-pretraining" / "data"), + ) + ).expanduser() + data_root = base / "cifar10" + print("CIFAR-10 root:", data_root, flush=True) + if not (data_root / "cifar-10-batches-py").is_dir(): + raise FileNotFoundError( + f"Existing CIFAR-10 dataset not found at {data_root}. " + "Pass --data-dir pointing to the parent of cifar-10-batches-py." + ) + + train_set = torchvision.datasets.CIFAR10( + root=str(data_root), + train=True, + download=False, + transform=train_transform, + ) + test_set = torchvision.datasets.CIFAR10( + root=str(data_root), + train=False, + download=False, + transform=test_transform, + ) + train_loader = DataLoader( + train_set, + batch_size=args.batch_size, + shuffle=True, + num_workers=args.num_workers, + pin_memory=True, + ) + test_loader = DataLoader( + test_set, + batch_size=args.batch_size, + shuffle=False, + num_workers=args.num_workers, + pin_memory=True, + ) + + classifier = nn.Linear(512, 10).to(device) + nn.init.normal_(classifier.weight, mean=0.0, std=0.01) + nn.init.zeros_(classifier.bias) + optimizer = torch.optim.SGD( + classifier.parameters(), + lr=args.lr, + momentum=0.9, + weight_decay=0.0, + nesterov=True, + ) + if args.schedule == "step": + scheduler = torch.optim.lr_scheduler.MultiStepLR( + optimizer, + milestones=[60, 80], + gamma=0.1, + ) + else: + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, + T_max=args.epochs * len(train_loader), + ) + + criterion = nn.CrossEntropyLoss() + history_path = output_dir / "metrics.csv" + best_accuracy = ( + -1.0 + ) # Diagnostic only; do not select checkpoints using test accuracy. + + with history_path.open("w", newline="") as file: + writer = csv.writer(file) + writer.writerow(["epoch", "train_loss", "test_accuracy", "lr"]) + for epoch in range(args.epochs): + classifier.eval() # Match the reference evaluation procedure. + total_loss = 0.0 + total_seen = 0 + for images, labels in train_loader: + images = images.to(device, non_blocking=True) + labels = labels.to(device, non_blocking=True) + with torch.no_grad(): + features = backbone(images) + logits = classifier(features) + loss = criterion(logits, labels) + optimizer.zero_grad(set_to_none=True) + loss.backward() + optimizer.step() + if args.schedule == "cosine": + scheduler.step() + total_loss += loss.item() * labels.size(0) + total_seen += labels.size(0) + + classifier.eval() + correct = 0 + tested = 0 + with torch.no_grad(): + for images, labels in test_loader: + images = images.to(device, non_blocking=True) + labels = labels.to(device, non_blocking=True) + predictions = classifier(backbone(images)).argmax(dim=1) + correct += (predictions == labels).sum().item() + tested += labels.size(0) + + accuracy = correct / tested + current_lr = optimizer.param_groups[0]["lr"] + writer.writerow([epoch + 1, total_loss / total_seen, accuracy, current_lr]) + file.flush() + best_accuracy = max(best_accuracy, accuracy) + print( + f"Epoch {epoch + 1:3d}/{args.epochs} | " + f"loss={total_loss / total_seen:.4f} | " + f"test_top1={accuracy:.2%} | best={best_accuracy:.2%} | " + f"lr={current_lr:.5g}", + flush=True, + ) + if args.schedule == "step": + scheduler.step() + + torch.save( + { + "classifier": classifier.state_dict(), + "epoch": args.epochs, + "accuracy": accuracy, + "source_checkpoint": str(args.checkpoint), + }, + output_dir / "last_linear_probe.pt", + ) + print(f"Final test accuracy: {accuracy:.2%}") + print(f"Best observed test accuracy: {best_accuracy:.2%} (diagnostic only)") + print(f"Results: {history_path}") + + +if __name__ == "__main__": + main() diff --git a/benchmarks/cifar10/ressl-resnet18.py b/benchmarks/cifar10/ressl-resnet18.py new file mode 100644 index 000000000..d8a097cc0 --- /dev/null +++ b/benchmarks/cifar10/ressl-resnet18.py @@ -0,0 +1,258 @@ +"""ReSSL pretraining on CIFAR-10 using stable_pretraining. + +Trains a ResNet-18 with asymmetric augmentations, SplitBatchNorm, an EMA +teacher, and a queue of teacher projections. Uses the composable +``stable_pretraining.forward.ressl`` forward function and online linear/KNN +probes to monitor representation quality during pretraining. + +Final frozen-backbone linear evaluation is performed separately. +""" + +import sys +from pathlib import Path + +import lightning as pl +import torch +from torch import nn +from lightning.pytorch.loggers import WandbLogger +import torchmetrics +import torchvision + +import stable_pretraining as spt +from stable_pretraining.backbone.ressl import ReSSLTeacherStudentWrapper +from stable_pretraining.backbone.split_batchnorm import SplitBatchNorm +from stable_pretraining.data import transforms +from stable_pretraining.callbacks.queues import UnsortedQueue +from stable_pretraining import forward + +sys.path.append(str(Path(__file__).resolve().parent.parent)) +from utils import get_data_dir + + +CIFAR10_STATS = { + "mean": [0.4914, 0.4822, 0.4465], + "std": [0.2023, 0.1994, 0.2010], +} + +NUM_DEVICES = 1 +BATCH_SIZE = 256 +MAX_EPOCHS = 200 +WARMUP_EPOCHS = 5 +NUM_SPLITS = 8 + +GLOBAL_BATCH_SIZE = BATCH_SIZE * NUM_DEVICES + + +def replace_batchnorm(module: nn.Module, num_splits: int = NUM_SPLITS) -> None: + """Recursively replace BatchNorm2d layers with SplitBatchNorm in place. + + Preserve each layer's configuration and existing state while enabling + independent batch statistics across equally sized input splits. + + Args: + module: Network whose BatchNorm2d layers will be replaced. + num_splits: Number of splits used during training. + """ + for name, child in module.named_children(): + if isinstance(child, nn.BatchNorm2d): + replacement = SplitBatchNorm( + child.num_features, + num_splits=num_splits, + eps=child.eps, + momentum=child.momentum, + affine=child.affine, + track_running_stats=child.track_running_stats, + ) + replacement.load_state_dict(child.state_dict()) + setattr(module, name, replacement) + else: + replace_batchnorm(child, num_splits) + + +def main(): + pl.seed_everything(42, workers=True) + + # ReSSL uses asymmetric views: the teacher sees weak augmentations and + # the student sees strong augmentations. The ordering is required by + # forward.ressl (views[0] = weak; views[1] = strong). + weak_transform = transforms.Compose( + transforms.RandomResizedCrop((32, 32), scale=(0.2, 1.0)), + transforms.RandomHorizontalFlip(p=0.5), + transforms.ToImage(**CIFAR10_STATS), + ) + strong_transform = transforms.Compose( + 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.PILGaussianBlur(sigma=(0.1, 2.0), p=0.5), + transforms.ToImage(**CIFAR10_STATS), + ) + train_transform = transforms.MultiViewTransform([weak_transform, strong_transform]) + val_transform = transforms.Compose(transforms.ToImage(**CIFAR10_STATS)) + + 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, + ) + train_dataset = spt.data.FromTorchDataset( + cifar_train, + names=["image", "label"], + transform=train_transform, + ) + val_dataset = spt.data.FromTorchDataset( + cifar_val, + names=["image", "label"], + transform=val_transform, + ) + train_loader = torch.utils.data.DataLoader( + train_dataset, + batch_size=BATCH_SIZE, + num_workers=4, + drop_last=True, + shuffle=True, + ) + val_loader = torch.utils.data.DataLoader( + val_dataset, + batch_size=BATCH_SIZE, + num_workers=4, + ) + + # Schedule the warmup and cosine decay by optimizer step, accounting + # for the global batch size when training on multiple devices. + steps_per_epoch = len(train_dataset) // GLOBAL_BATCH_SIZE + warmup_steps = WARMUP_EPOCHS * steps_per_epoch + max_steps = MAX_EPOCHS * steps_per_epoch + print(f"Steps/epoch: {steps_per_epoch}; warmup: {warmup_steps}; total: {max_steps}") + data = spt.data.DataModule(train=train_loader, val=val_loader) + + # Use a CIFAR-sized ResNet-18 without its classification head. Replace + # BatchNorm2d with SplitBatchNorm for the teacher's shuffled batches. + # Both backbone and projector maintain momentum-teacher copies. + base = spt.backbone.from_torchvision("resnet18", low_resolution=True) + base.fc = nn.Identity() + replace_batchnorm(base) + backbone = ReSSLTeacherStudentWrapper( + base, + warm_init=True, + base_ema_coefficient=0.99, + final_ema_coefficient=0.99, + ) + projector = ReSSLTeacherStudentWrapper( + nn.Sequential( + nn.Linear(512, 2048), + nn.ReLU(inplace=True), + nn.Linear(2048, 128), + ), + warm_init=True, + base_ema_coefficient=0.99, + final_ema_coefficient=0.99, + ) + + # A full, randomly initialized memory bank matches the original ReSSL setup. + # Initialize after seeding and register as a child module for checkpointing. + queue = UnsortedQueue(max_length=4096, shape=128) + with torch.no_grad(): + initial_keys = torch.nn.functional.normalize(torch.randn(4096, 128), dim=-1) + queue.append(initial_keys) + + # Scale the base learning rate with the global batch size. The teacher + # and student temperatures control the relational target distributions. + module = spt.Module( + backbone=backbone, + projector=projector, + forward=forward.ressl, + ressl_loss=spt.losses.ReSSLLoss( + temperature_student=0.1, + temperature_teacher=0.04, + ), + queue=queue, + optim={ + "optimizer": { + "type": "SGD", + "exclude_bias_norm": False, + "momentum": 0.9, + "lr": 0.06 * GLOBAL_BATCH_SIZE / 256, + "weight_decay": 5e-4, + }, + "scheduler": { + "type": "LinearWarmupCosineAnnealingLR", + "warmup_steps": warmup_steps, + "max_steps": max_steps, + "warmup_start_lr": 0.0, + "eta_min": 0.0, + }, + "interval": "step", + }, + ) + + # Ensure the queue's state is tracked by Lightning checkpoints. + assert "queue.out" in module.state_dict(), "Queue was not registered" + + # Online probes track representation quality during pretraining; final + # linear evaluation uses a separate frozen-backbone training procedure. + linear_probe = spt.callbacks.OnlineProbe( + module, + name="linear_probe", + input="embedding", + target="label", + probe=nn.Linear(512, 10), + loss=nn.CrossEntropyLoss(), + metrics={ + "top1": torchmetrics.classification.MulticlassAccuracy(10), + "top5": torchmetrics.classification.MulticlassAccuracy(10, top_k=5), + }, + ) + knn_probe = spt.callbacks.OnlineKNN( + name="knn_probe", + input="embedding", + target="label", + queue_length=20000, + metrics={"accuracy": torchmetrics.classification.MulticlassAccuracy(10)}, + input_dim=512, + k=10, + ) + + logger = WandbLogger( + entity="stable-ssl", + project="cifar10-ressl", + name="ressl-resnet18", + log_model=False, + ) + trainer = pl.Trainer( + accelerator="gpu", + devices=NUM_DEVICES, + strategy="ddp", + max_epochs=MAX_EPOCHS, + num_sanity_val_steps=0, + callbacks=[ + knn_probe, + linear_probe, + spt.callbacks.TeacherStudentCallback( + update_frequency=1, + update_after_backward=False, + ), + ], + precision="32-true", + logger=logger, + enable_checkpointing=True, + ) + manager = spt.Manager(trainer=trainer, module=module, data=data) + manager() + + +if __name__ == "__main__": + main() diff --git a/docs/.DS_Store b/docs/.DS_Store deleted file mode 100644 index 1742c6d33..000000000 Binary files a/docs/.DS_Store and /dev/null differ diff --git a/docs/source/api/forward.rst b/docs/source/api/forward.rst index accbccd09..d5053bede 100644 --- a/docs/source/api/forward.rst +++ b/docs/source/api/forward.rst @@ -187,6 +187,45 @@ BYOL in_features: 4096 out_features: 256 +ReSSL +~~~~~~ + +.. autofunction:: ressl + +**Required Module Attributes:** + +- ``backbone``: Teacher–student wrapper for feature extraction +- ``projector``: Teacher–student wrapper for projecting backbone features +- ``ressl_loss``: ReSSL relational cross-entropy loss +- ``queue``: ``UnsortedQueue`` prefilled with L2-normalized keys of the + projection dimension + +**Key Features:** + +- Expects the weak teacher view at ``views[0]`` and the strong student + view at ``views[1]`` +- Matches student and teacher similarity distributions over a queue of + teacher projections +- Gathers teacher projections across ranks during distributed training + and appends them to the queue after computing the loss +- Uses ``TeacherStudentCallback`` for EMA updates. ``spt.Manager`` adds + it automatically. When calling Lightning's ``Trainer.fit`` directly, + register the callback on the trainer. + +**Example Config:** + +.. code-block:: yaml + + module: + forward: stable_pretraining.forward.ressl + backbone: ... # ReSSLTeacherStudentWrapper + projector: ... # ReSSLTeacherStudentWrapper + queue: ... # UnsortedQueue prefilled with L2-normalized keys + ressl_loss: + _target_: stable_pretraining.losses.ReSSLLoss + temperature_student: 0.1 + temperature_teacher: 0.04 + VICReg ~~~~~~ diff --git a/docs/source/api/losses.rst b/docs/source/api/losses.rst index 0b487a840..315e60c98 100644 --- a/docs/source/api/losses.rst +++ b/docs/source/api/losses.rst @@ -10,5 +10,6 @@ stable_pretraining.losses NTXEntLoss NegativeCosineSimilarity + ReSSLLoss VICRegLoss BarlowTwinsLoss diff --git a/docs/source/api/methods.rst b/docs/source/api/methods.rst index d582fa39a..ea18784c1 100644 --- a/docs/source/api/methods.rst +++ b/docs/source/api/methods.rst @@ -69,6 +69,7 @@ online clustering to learn representations without negative pairs. DINOv2 DINOv3 iBOT + ReSSL SwAV MSN Data2Vec diff --git a/stable_pretraining/__init__.py b/stable_pretraining/__init__.py index 1438bed7e..1511371b3 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"), + "ReSSL": ("stable_pretraining.methods.ressl", "ReSSL"), "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", + "ReSSL", "SimCLR", "SwAV", "VICReg", diff --git a/stable_pretraining/__init__.pyi b/stable_pretraining/__init__.pyi index 3fce470c4..99c58629a 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.ressl import ReSSL as ReSSL 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/backbone/__init__.py b/stable_pretraining/backbone/__init__.py index 4f375c916..30ed66e9e 100644 --- a/stable_pretraining/backbone/__init__.py +++ b/stable_pretraining/backbone/__init__.py @@ -72,6 +72,14 @@ vit_intern6b_patch14_448, ) +from .split_batchnorm import ( + SplitBatchNorm, +) + +from .ressl import ( + ReSSLTeacherStudentWrapper, +) + from .aggregator import TensorAggregator from .decoders import CNNImageDecoder, ViTImageDecoder, build_image_decoder from . import video # noqa: F401 — video encoders live under sp.backbone.video.* @@ -96,6 +104,8 @@ vit_hf, MultiHeadAttentiveProbe, LinearProbe, + SplitBatchNorm, + ReSSLTeacherStudentWrapper, AutoLinearClassifier, EfficientMaskedTimmViT, register_lr_scale_hook, diff --git a/stable_pretraining/backbone/ressl.py b/stable_pretraining/backbone/ressl.py new file mode 100644 index 000000000..f9f021de9 --- /dev/null +++ b/stable_pretraining/backbone/ressl.py @@ -0,0 +1,51 @@ +"""Teacher-student wrapper for Relational Self-Supervised Learning. + +This module provides an EMA teacher that updates model parameters +without copying the student's BatchNorm running statistics. +""" + +import stable_pretraining as spt +import torch + + +class ReSSLTeacherStudentWrapper(spt.TeacherStudentWrapper): + """Teacher-student wrapper with independent BatchNorm statistics. + + ReSSL updates teacher parameters using an exponential moving average + (EMA) of student parameters while maintaining independent BatchNorm + running statistics for the teacher. + + Unlike the standard TeacherStudentWrapper, this implementation + does not synchronize buffers between the student and teacher. + """ + + @torch.no_grad() + def update_teacher(self): + """Update teacher parameters using exponential moving averaging. + + Applies the update: + + teacher = momentum * teacher + (1 - momentum) * student + + BatchNorm running statistics and other buffers are left unchanged. + + The update is skipped during evaluation, when the teacher and + student share parameters, or when EMA momentum equals 1.0. + + Raises: + RuntimeError: If student and teacher parameter counts differ. + """ + if not self.training or self.teacher is self.student: + return + + momentum = float(self.ema_coefficient) + if momentum == 1.0: + return + + student_params = list(self.student.parameters()) + teacher_params = list(self.teacher.parameters()) + if len(student_params) != len(teacher_params): + raise RuntimeError("Student and teacher parameter counts differ") + + for student_param, teacher_param in zip(student_params, teacher_params): + teacher_param.lerp_(student_param, 1.0 - momentum) diff --git a/stable_pretraining/backbone/split_batchnorm.py b/stable_pretraining/backbone/split_batchnorm.py new file mode 100644 index 000000000..5ebfa9428 --- /dev/null +++ b/stable_pretraining/backbone/split_batchnorm.py @@ -0,0 +1,87 @@ +"""Split Batch Normalization for self-supervised learning. + +This module provides batch normalization that computes statistics +independently across equally sized splits of the input batch. +""" + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class SplitBatchNorm(nn.BatchNorm2d): + """Batch normalization with independent statistics for batch splits. + + During training, divides the input batch into equally sized splits + and normalizes each split using its own batch statistics. Running + statistics are averaged across splits for use during evaluation. + + During evaluation, applies standard BatchNorm2d using the + accumulated running statistics. + + Parameters + ---------- + num_features : int + Number of input channels. + num_splits : int, default=8 + Number of equally sized batch splits. + **kwargs + Additional arguments passed to nn.BatchNorm2d. + + Raises: + ------ + ValueError + If num_splits is not a positive integer, the training batch size + is not divisible by num_splits, or unsupported BatchNorm2d + options are requested. + + Notes: + ----- + Input and output tensors have shape (N, C, H, W). + This implementation requires affine=True and track_running_stats=True. + """ + + def __init__(self, num_features: int, num_splits: int = 8, **kwargs): + if ( + not isinstance(num_splits, int) + or isinstance(num_splits, bool) + or num_splits <= 0 + ): + raise ValueError("num_splits must be a positive integer") + super().__init__(num_features, **kwargs) + self.num_splits = num_splits + + def forward(self, input: torch.Tensor) -> torch.Tensor: + """Normalize each batch split independently during training.""" + if not self.training: + return super().forward(input) + + n, c, h, w = input.shape + if n % self.num_splits != 0: + raise ValueError( + f"Batch size {n} must be divisible by num_splits={self.num_splits}" + ) + + running_mean_split = self.running_mean.repeat(self.num_splits) + running_var_split = self.running_var.repeat(self.num_splits) + + output = F.batch_norm( + input.reshape(-1, c * self.num_splits, h, w), + running_mean_split, + running_var_split, + self.weight.repeat(self.num_splits), + self.bias.repeat(self.num_splits), + True, + self.momentum, + self.eps, + ).reshape(n, c, h, w) + + with torch.no_grad(): + self.running_mean.copy_( + running_mean_split.reshape(self.num_splits, c).mean(dim=0) + ) + self.running_var.copy_( + running_var_split.reshape(self.num_splits, c).mean(dim=0) + ) + + return output diff --git a/stable_pretraining/forward.py b/stable_pretraining/forward.py index f33f09241..5685f2194 100644 --- a/stable_pretraining/forward.py +++ b/stable_pretraining/forward.py @@ -42,6 +42,7 @@ import torch from .callbacks.queue import find_or_create_queue_callback, OnlineQueue +from stable_pretraining.utils import all_gather def _get_views_list(batch: dict): @@ -533,6 +534,120 @@ def barlow_twins(self, batch: dict[str, Any], stage: str) -> dict[str, torch.Ten return out +def ressl(self, batch: dict[str, Any], stage: str) -> dict[str, torch.Tensor]: + """Forward function for ReSSL (Relational Self-Supervised Learning). + + ReSSL learns representations by matching student and momentum-teacher + similarity distributions over a memory queue. The teacher processes a + weakly augmented view, while the student processes a strongly augmented + view of the same images. + + During training, teacher projections are gathered across distributed + processes and appended to the queue after computing the loss. + + Args: + self: Module instance (automatically bound) with required attributes: + - backbone: Teacher-student wrapper for feature extraction. + - projector: Teacher-student wrapper for projection. + - ressl_loss: ReSSL relational distribution matching loss. + - queue: Memory queue containing teacher projections. + batch: Input batch containing either two augmented views or a single + image. Multi-view batches must provide exactly two views: + - views[0]: Weak augmentation for the teacher. + - views[1]: Strong augmentation for the student. + Each view contains an "image" tensor of shape [N, C, H, W] + and may contain a "label" tensor of shape [N]. + stage: Training stage ("train", "val", or "test"). + + Returns: + Dictionary containing: + - "embedding": Detached student backbone features. + - "loss": ReSSL loss during multi-view training only. + - "label": Labels if present in the input batch. + + Raises: + ValueError: If a multi-view batch does not contain exactly two views. + + Notes: + Teacher features are computed without gradients. The local teacher + batch is shuffled before encoding to randomize SplitBatchNorm groups. + The memory queue is updated only during training. + + Single-view evaluation returns student embeddings without computing + the ReSSL loss. Multi-view evaluation returns student embeddings for + the strongly augmented view, also without computing the loss. + + Teacher parameters are updated via EMA of student parameters by the + TeacherStudentCallback, independently of this function. + """ + out = {} + views = _get_views_list(batch) + + if views is None: + # Single-view evaluation returns student features without SSL loss. + if "label" in batch: + out["label"] = batch["label"] + + with torch.no_grad(): + features = self.backbone.forward_student(batch["image"]) + + out["embedding"] = features.detach() + return out + + if len(views) != 2: + raise ValueError(f"ReSSL requires two views, got {len(views)}") + + weak_view = views[0]["image"] + strong_view = views[1]["image"] + + if "label" in views[0]: + out["label"] = views[0]["label"] + + if not self.training: + with torch.no_grad(): + student_features = self.backbone.forward_student(strong_view) + out["embedding"] = student_features.detach() + return out + + student_features = self.backbone.forward_student(strong_view) + out["embedding"] = student_features.detach() + + # Shuffle the local teacher batch to randomize SplitBatchNorm groups. + with torch.no_grad(): + shuffle = torch.randperm(weak_view.shape[0], device=weak_view.device) + unshuffle = torch.argsort(shuffle) + teacher_features = self.backbone.forward_teacher(weak_view[shuffle]) + teacher_projection = self.projector.forward_teacher(teacher_features) + teacher_projection = torch.nn.functional.normalize(teacher_projection, dim=-1)[ + unshuffle + ] + + student_projection = self.projector.forward_student(student_features) + student_projection = torch.nn.functional.normalize(student_projection, dim=-1) + + # Clone the queue to protect autograd from the subsequent in-place update. + queue_snapshot = self.queue.get().detach().clone() + out["loss"] = self.ressl_loss( + student_projection, + teacher_projection, + queue_snapshot, + ) + + with torch.no_grad(): + keys = torch.cat(all_gather(teacher_projection.detach()), dim=0) + self.queue.append(keys) + + self.log( + f"{stage}/loss", + out["loss"], + on_step=True, + on_epoch=True, + sync_dist=True, + prog_bar=True, + ) + return out + + def swav(self, batch: dict[str, Any], stage: str) -> dict[str, torch.Tensor]: """Forward function for SwAV (Swapping Assignments between Views). diff --git a/stable_pretraining/losses/__init__.py b/stable_pretraining/losses/__init__.py index 37eff8da9..85145c91a 100644 --- a/stable_pretraining/losses/__init__.py +++ b/stable_pretraining/losses/__init__.py @@ -25,6 +25,9 @@ # Reconstruction losses from .reconstruction import mae, MAELoss +# ReSSL loss +from .ressl import ReSSLLoss + # Utilities from .utils import ( sinkhorn_knopp, @@ -53,4 +56,6 @@ "off_diagonal", "NegativeCosineSimilarity", "VCRegLoss", + # ReSSL + "ReSSLLoss", ] diff --git a/stable_pretraining/losses/ressl.py b/stable_pretraining/losses/ressl.py new file mode 100644 index 000000000..3f2c691c8 --- /dev/null +++ b/stable_pretraining/losses/ressl.py @@ -0,0 +1,84 @@ +"""Relational self-supervised learning losses. + +This module contains the ReSSL loss, which learns representations by +matching student and teacher similarity distributions over a memory queue. +""" + +import torch +import torch.nn.functional as F + + +class ReSSLLoss(torch.nn.Module): + """Relational Self-Supervised Learning (ReSSL) loss. + + Computes cross-entropy between the student and teacher similarity + distributions over a shared memory queue of teacher projections. + + The teacher distribution serves as a fixed target, while the student + distribution is optimized to match it. Separate temperatures control + the sharpness of the two distributions. + + Args: + temperature_student: Temperature for the student distribution. + temperature_teacher: Temperature for the teacher distribution. + + Raises: + ValueError: If either temperature is not strictly positive. + """ + + def __init__( + self, + temperature_student: float = 0.1, + temperature_teacher: float = 0.05, + ): + super().__init__() + + if temperature_student <= 0 or temperature_teacher <= 0: + raise ValueError("ReSSL temperatures must be strictly positive") + + self.temperature_student = temperature_student + self.temperature_teacher = temperature_teacher + + def forward( + self, + student_embeddings: torch.Tensor, + teacher_embeddings: torch.Tensor, + queue: torch.Tensor, + ) -> torch.Tensor: + """Compute relational cross-entropy between student and teacher. + + Args: + student_embeddings: Student projections of shape (B, D). + teacher_embeddings: Teacher projections of shape (B, D). + queue: Memory queue of teacher projections of shape (K, D). + + Returns: + Scalar cross-entropy loss averaged over the batch. + + Shape: + - student_embeddings: (B, D) + - teacher_embeddings: (B, D) + - queue: (K, D) + - output: scalar + + Notes: + B is the batch size, D is the projection dimension, and K + is the queue size. Embeddings and queue entries are expected + to be L2-normalized before calling this function. + + Gradients flow through the student distribution only. + """ + queue = queue.detach() + student_logits = student_embeddings @ queue.T + student_log_probs = F.log_softmax( + student_logits.float() / self.temperature_student, + dim=-1, + ) + + teacher_logits = teacher_embeddings.detach() @ queue.T + teacher_probs = F.softmax( + teacher_logits.float() / self.temperature_teacher, + dim=-1, + ) + + return -(teacher_probs * student_log_probs).sum(dim=-1).mean() diff --git a/stable_pretraining/methods/__init__.py b/stable_pretraining/methods/__init__.py index 7cc3209bb..36a272e45 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 .ressl import ReSSL from .salt import SALT from .simclr import SimCLR from .simmim import SimMIM @@ -56,6 +57,7 @@ "NNCLR", "PIRL", "PMSN", + "ReSSL", "SALT", "SimCLR", "SimMIM", diff --git a/stable_pretraining/methods/ressl.py b/stable_pretraining/methods/ressl.py new file mode 100644 index 000000000..87c599729 --- /dev/null +++ b/stable_pretraining/methods/ressl.py @@ -0,0 +1,132 @@ +"""ReSSL: Relational Self-Supervised Learning. + +Student-teacher self-supervised learning with relational distributions over +a memory queue of teacher projections. + +Reference: + Zheng et al., "ReSSL: Relational Self-Supervised Learning with + Weak Augmentation," NeurIPS 2021. +""" + +from typing import Any, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from stable_pretraining import Module +from stable_pretraining.backbone.ressl import ReSSLTeacherStudentWrapper +from stable_pretraining.callbacks.queues import UnsortedQueue +from stable_pretraining.forward import ressl +from stable_pretraining.losses import ReSSLLoss + + +class ReSSL(Module): + """Relational Self-Supervised Learning with an EMA teacher and memory queue. + + The student learns to match the teacher's similarity distribution over + stored teacher projections. The teacher processes weak augmentations, + while the student processes strong augmentations. + + Teacher parameters are updated separately through EMA, for example + by TeacherStudentCallback. + + Args: + encoder_name: Timm backbone name or instantiated PyTorch backbone. + encoder_dim: Backbone feature dimension. Inferred from num_features + when available. + temperature_teacher: Teacher similarity-distribution temperature. + temperature_student: Student similarity-distribution temperature. + queue_size: Number of teacher projections retained in the queue. + ema_decay_start: Initial teacher EMA momentum. + ema_decay_end: Final teacher EMA momentum. + pretrained: Whether to use pretrained weights for a named backbone. + """ + + def __init__( + self, + encoder_name: Union[str, nn.Module] = "resnet18", + encoder_dim: int | None = None, + temperature_teacher: float = 0.05, + temperature_student: float = 0.1, + queue_size: int = 256, + ema_decay_start: float = 0.996, + ema_decay_end: float = 1.0, + pretrained: bool = False, + ): + super().__init__() + + if queue_size <= 0: + raise ValueError("queue_size must be positive") + + if isinstance(encoder_name, str): + import timm + + base = timm.create_model( + encoder_name, + num_classes=0, + pretrained=pretrained, + ) + else: + base = encoder_name + + if encoder_dim is None: + encoder_dim = getattr(base, "num_features", None) + + if not isinstance(encoder_dim, int) or encoder_dim <= 0: + raise ValueError( + "encoder_dim must be a positive integer. Provide it " + "explicitly if the backbone has no num_features attribute." + ) + + self.temperature_teacher = temperature_teacher + self.temperature_student = temperature_student + + self.backbone = ReSSLTeacherStudentWrapper( + base, + warm_init=True, + base_ema_coefficient=ema_decay_start, + final_ema_coefficient=ema_decay_end, + ) + + self.projection_head = ReSSLTeacherStudentWrapper( + nn.Sequential( + nn.Linear(encoder_dim, 4096), + nn.ReLU(), + nn.Linear(4096, 512), + ), + warm_init=True, + base_ema_coefficient=ema_decay_start, + final_ema_coefficient=ema_decay_end, + ) + + # Initialize the queue with normalized random teacher keys. + self.queue = UnsortedQueue(max_length=queue_size, shape=512) + with torch.no_grad(): + initial_keys = F.normalize( + torch.randn(queue_size, 512), + dim=-1, + ) + self.queue.append(initial_keys) + + self.ressl_loss = ReSSLLoss( + temperature_student=temperature_student, + temperature_teacher=temperature_teacher, + ) + + @property + def projector(self) -> ReSSLTeacherStudentWrapper: + """Expose the projection head to the shared forward function.""" + return self.projection_head + + def forward(self, batch: dict[str, Any], stage: str) -> dict[str, torch.Tensor]: + """Return student embeddings and the ReSSL loss during training. + + Args: + batch: A single image batch or two views ordered weak then strong. + stage: Stage name supplied by the training loop. + + Returns: + A dictionary with embeddings and, during two-view training, loss. + """ + return ressl(self, batch, stage) diff --git a/stable_pretraining/tests/distributed/_ressl_lightning_smoke.py b/stable_pretraining/tests/distributed/_ressl_lightning_smoke.py new file mode 100644 index 000000000..bc53aa0d4 --- /dev/null +++ b/stable_pretraining/tests/distributed/_ressl_lightning_smoke.py @@ -0,0 +1,42 @@ +"""Run the Lightning DDP smoke test in a separate process.""" + +import sys +from pathlib import Path + +import lightning as pl +import torch +from torch.utils.data import DataLoader + +from stable_pretraining.tests.distributed.test_ressl_ddp import ( + _CheckQueueCallback, + _make_model, + _TwoViews, +) + + +def main(): + pl.seed_everything(42) + model = _make_model(queue_size=7) + loader = DataLoader(_TwoViews(), batch_size=2, num_workers=0) + + trainer = pl.Trainer( + accelerator="cpu", + devices=2, + strategy="ddp", + max_steps=3, + callbacks=[_CheckQueueCallback()], + logger=False, + enable_checkpointing=False, + enable_progress_bar=False, + enable_model_summary=False, + num_sanity_val_steps=0, + default_root_dir=Path(sys.argv[1]), + ) + trainer.fit(model, train_dataloaders=loader) + + assert trainer.global_step == 3 + assert bool(torch.isfinite(model.queue.out).all()) + + +if __name__ == "__main__": + main() diff --git a/stable_pretraining/tests/distributed/test_ressl_ddp.py b/stable_pretraining/tests/distributed/test_ressl_ddp.py new file mode 100644 index 000000000..c275ed1b9 --- /dev/null +++ b/stable_pretraining/tests/distributed/test_ressl_ddp.py @@ -0,0 +1,225 @@ +"""CPU distributed and Lightning DDP integration tests for ReSSL.""" + +import lightning as pl +import pytest +import torch +import torch.distributed as dist +from torch import nn +from torch.utils.data import Dataset + +import stable_pretraining as spt +from stable_pretraining import forward +from stable_pretraining.backbone.ressl import ReSSLTeacherStudentWrapper +from stable_pretraining.callbacks.queues import UnsortedQueue +from stable_pretraining.utils import all_gather +from stable_pretraining.tests.distributed import _dist_harness as H +import subprocess +import sys + + +class _TinyEncoder(nn.Module): + """BatchNorm-free encoder to keep the CPU tests fast.""" + + def __init__(self): + super().__init__() + self.net = nn.Sequential(nn.Flatten(), nn.Linear(4, 8), nn.ReLU()) + + def forward(self, images): + return self.net(images) + + +class _TwoViews(Dataset): + def __len__(self): + return 32 + + def __getitem__(self, index): + image = torch.arange(4, dtype=torch.float32).reshape(1, 2, 2) + image = image / 4 + index / 32 + label = torch.tensor(index % 2) + return { + "views": [ + {"image": image, "label": label}, + {"image": image + 0.1, "label": label}, + ] + } + + +def _make_model(queue_size=7): + backbone = ReSSLTeacherStudentWrapper( + _TinyEncoder(), + warm_init=True, + base_ema_coefficient=0.9, + final_ema_coefficient=0.9, + ) + projector = ReSSLTeacherStudentWrapper( + nn.Linear(8, 4), + warm_init=True, + base_ema_coefficient=0.9, + final_ema_coefficient=0.9, + ) + queue = UnsortedQueue(max_length=queue_size, shape=4) + with torch.no_grad(): + queue.append( + torch.nn.functional.normalize( + torch.randn(queue_size, 4), + dim=-1, + ) + ) + return spt.Module( + backbone=backbone, + projector=projector, + queue=queue, + ressl_loss=spt.losses.ReSSLLoss( + temperature_student=0.1, + temperature_teacher=0.04, + ), + forward=forward.ressl, + optim={"optimizer": {"type": "SGD", "lr": 0.01}}, + ) + + +def _assert_queue_synced(queue, world_size): + """Compare the real queue's storage, pointer, and flags on all ranks.""" + for name, buffer in queue.named_buffers(): + # Compare bytewise representations to support bool and integer buffers. + values = buffer.detach().contiguous().reshape(-1) + gathered = [torch.empty_like(values) for _ in range(world_size)] + dist.all_gather(gathered, values) + for other in gathered[1:]: + torch.testing.assert_close(other, gathered[0], msg=f"queue.{name}") + + +def _worker_gather_queue(rank, world_size): + """Validate rank ordering, real queue contents, and circular wraparound.""" + queue = UnsortedQueue(max_length=7, shape=4) + reference = UnsortedQueue(max_length=7, shape=4) + + for step in range(5): + local = torch.full((2, 4), float(10 * step + rank)) + gathered = torch.cat(all_gather(local), dim=0) + expected_keys = torch.cat( + [torch.full((2, 4), float(10 * step + r)) for r in range(world_size)] + ) + torch.testing.assert_close(gathered, expected_keys) + queue.append(gathered) + reference.append(expected_keys) + for name, expected in reference.named_buffers(): + torch.testing.assert_close(getattr(queue, name), expected) + _assert_queue_synced(queue, world_size) + + assert bool(queue.filled) + assert int(queue.pointer) == (5 * 2 * world_size) % queue.max_length + + # An entire global batch larger than capacity must retain only its tail. + oversized = torch.full((8, 4), float(rank)) + gathered = torch.cat(all_gather(oversized), dim=0) + queue.append(gathered) + torch.testing.assert_close(queue.out, gathered[-queue.max_length :]) + assert int(queue.pointer) == 0 + _assert_queue_synced(queue, world_size) + + +def _worker_real_forward(rank, world_size): + """Exercise the actual composable ReSSL forward and distributed queue.""" + torch.manual_seed(123) + model = _make_model(queue_size=7) + model.train() + model.log = lambda *args, **kwargs: None # no Trainer in harness workers + _assert_queue_synced(model.queue, world_size) + + optimizer = torch.optim.SGD( + [p for p in model.parameters() if p.requires_grad], + lr=0.01, + ) + initial_student = next(model.backbone.student.parameters()).detach().clone() + + for step in range(4): + torch.manual_seed(1000 + rank * 100 + step) + weak = torch.randn(2, 1, 2, 2) + strong = weak + 0.1 + batch = {"views": [{"image": weak}, {"image": strong}]} + + optimizer.zero_grad() + output = forward.ressl(model, batch, "train") + loss = output["loss"] + assert loss.ndim == 0 and bool(torch.isfinite(loss)) + loss.backward() + + grads = [p.grad for p in model.parameters() if p.requires_grad] + assert any(grad is not None for grad in grads) + for grad in grads: + if grad is not None: + assert bool(torch.isfinite(grad).all()) + dist.all_reduce(grad) + grad.div_(world_size) + + optimizer.step() + model.backbone.update_teacher() + model.projector.update_teacher() + _assert_queue_synced(model.queue, world_size) + + assert not torch.equal( + initial_student, + next(model.backbone.student.parameters()).detach(), + ), "Student parameters did not update" + assert bool(model.queue.filled) + + snapshot = {name: value.clone() for name, value in model.queue.named_buffers()} + model.eval() + output = forward.ressl( + model, + {"image": torch.randn(2, 1, 2, 2)}, + "val", + ) + assert "loss" not in output + for name, value in model.queue.named_buffers(): + torch.testing.assert_close(value, snapshot[name]) + + +class _CheckQueueCallback(pl.Callback): + """Assert queue consistency inside *each* Lightning DDP rank.""" + + def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx): + assert bool(torch.isfinite(outputs["loss"])) + assert dist.is_initialized() + assert dist.get_world_size() == 2 + _assert_queue_synced(pl_module.queue, dist.get_world_size()) + + +@pytest.mark.unit +def test_ressl_gather_queue_wraparound_ddp(): + H.run_distributed( + _worker_gather_queue, + world_size=2, + backend="gloo", + timeout=180, + ) + + +@pytest.mark.unit +def test_ressl_forward_backward_queue_ddp(): + H.run_distributed( + _worker_real_forward, + world_size=2, + backend="gloo", + timeout=180, + ) + + +@pytest.mark.unit +def test_ressl_lightning_ddp(tmp_path): + """Keep Lightning's distributed processes isolated from pytest.""" + assert not dist.is_initialized() + + subprocess.run( + [ + sys.executable, + "-m", + "stable_pretraining.tests.distributed._ressl_lightning_smoke", + str(tmp_path), + ], + check=True, + timeout=180, + ) + + assert not dist.is_initialized() diff --git a/stable_pretraining/tests/unit/test_ressl.py b/stable_pretraining/tests/unit/test_ressl.py new file mode 100644 index 000000000..69a893a73 --- /dev/null +++ b/stable_pretraining/tests/unit/test_ressl.py @@ -0,0 +1,299 @@ +"""Unit tests for ReSSL loss, EMA wrapper, queue, and distributed keys.""" + +import copy +import os +import tempfile + +import lightning as pl +from torch.utils.data import DataLoader + +import pytest +import torch +import torch.distributed as dist +import torch.multiprocessing as mp +from torch import nn +from torch.nn import functional as F +from unittest.mock import Mock + +import stable_pretraining as spt +from stable_pretraining.backbone.ressl import ReSSLTeacherStudentWrapper +from stable_pretraining.callbacks.queues import UnsortedQueue +from stable_pretraining.losses import ReSSLLoss +from stable_pretraining.methods import ReSSL +from stable_pretraining.utils import all_gather + +pytestmark = pytest.mark.unit + + +def test_ressl_loss_is_finite_and_differentiable(): + torch.manual_seed(0) + loss_fn = ReSSLLoss(temperature_student=0.1, temperature_teacher=0.04) + student = F.normalize(torch.randn(4, 8), dim=-1).detach().requires_grad_() + teacher = F.normalize(torch.randn(4, 8), dim=-1) + queue = F.normalize(torch.randn(16, 8), dim=-1) + + loss = loss_fn(student, teacher, queue) + assert loss.ndim == 0 + assert torch.isfinite(loss) + loss.backward() + assert student.grad is not None + assert torch.isfinite(student.grad).all() + assert teacher.grad is None + + +def test_ressl_loss_and_gradients_are_finite_for_extreme_logits(): + loss_fn = ReSSLLoss(temperature_student=1e-4, temperature_teacher=1e-4) + student = torch.tensor([[1.0, 0.0], [-1.0, 0.0]], requires_grad=True) + teacher = torch.tensor([[-1.0, 0.0], [1.0, 0.0]]) + queue = torch.tensor([[1.0, 0.0], [-1.0, 0.0]]) + + loss = loss_fn(student, teacher, queue) + + assert loss.ndim == 0 + assert torch.isfinite(loss) + + loss.backward() + + assert student.grad is not None + assert torch.isfinite(student.grad).all() + assert (student.grad.abs().sum(dim=1) > 0).all() + + +def test_ressl_loss_matches_manual_relational_cross_entropy(): + student = F.normalize(torch.tensor([[1.0, 2.0], [2.0, 1.0]]), dim=-1) + teacher = F.normalize(torch.tensor([[2.0, 1.0], [1.0, 2.0]]), dim=-1) + queue = F.normalize(torch.tensor([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]), dim=-1) + loss_fn = ReSSLLoss(temperature_student=0.1, temperature_teacher=0.04) + + targets = (teacher @ queue.T / 0.04).softmax(dim=-1) + log_probs = (student @ queue.T / 0.1).log_softmax(dim=-1) + expected = -(targets * log_probs).sum(dim=-1).mean() + torch.testing.assert_close(loss_fn(student, teacher, queue), expected) + + +def test_ressl_teacher_starts_equal_to_student(): + wrapper = ReSSLTeacherStudentWrapper( + nn.Linear(4, 3), + warm_init=True, + base_ema_coefficient=0.9, + final_ema_coefficient=0.9, + ) + for student, teacher in zip( + wrapper.student.parameters(), wrapper.teacher.parameters() + ): + torch.testing.assert_close(student, teacher) + + +def test_ressl_parameter_only_ema_does_not_copy_batchnorm_buffers(): + wrapper = ReSSLTeacherStudentWrapper( + nn.Sequential(nn.Linear(4, 4), nn.BatchNorm1d(4)), + warm_init=True, + base_ema_coefficient=0.9, + final_ema_coefficient=0.9, + ) + with torch.no_grad(): + for param in wrapper.student.parameters(): + param.fill_(1.0) + for param in wrapper.teacher.parameters(): + param.zero_() + wrapper.teacher[1].running_mean.fill_(7.0) + wrapper.student[1].running_mean.fill_(3.0) + + # Assumes update_teacher() uses the configured coefficient when called. + wrapper.update_teacher() + for param in wrapper.teacher.parameters(): + torch.testing.assert_close(param, torch.full_like(param, 0.1)) + torch.testing.assert_close(wrapper.teacher[1].running_mean, torch.full((4,), 7.0)) + + +def test_ressl_standalone_forward(): + class TinyEncoder(nn.Module): + num_features = 8 + + def __init__(self): + super().__init__() + self.net = nn.Sequential( + nn.Flatten(), + nn.Linear(4, 8), + ) + + def forward(self, x): + return self.net(x) + + model = ReSSL( + encoder_name=TinyEncoder(), + queue_size=16, + ) + model.train() + + weak = torch.randn(4, 1, 2, 2) + strong = torch.randn(4, 1, 2, 2) + + batch = {"views": [{"image": weak}, {"image": strong}]} + + model.log = Mock() + output = model(batch, stage="fit") + + assert isinstance(output, dict) + loss = output["loss"] + assert loss.ndim == 0 + assert torch.isfinite(loss) + loss.backward() + assert any(p.grad is not None for p in model.backbone.student.parameters()) + + +def test_ressl_manager_checkpoint_resume(tmp_path): + def make_model(): + return spt.ReSSL( + encoder_name=nn.Sequential( + nn.Flatten(), + nn.Linear(4, 8), + nn.BatchNorm1d(8), + ), + encoder_dim=8, + queue_size=11, + ema_decay_start=0.9, + ema_decay_end=0.9, + ) + + images = torch.randn(8, 1, 2, 2, generator=torch.Generator().manual_seed(0)) + + def make_data(): + samples = [ + {"views": [{"image": image + 2.0}, {"image": image - 2.0}]} + for image in images + ] + return spt.data.DataModule(train=DataLoader(samples, batch_size=4)) + + def make_trainer(max_epochs, callbacks=()): + return pl.Trainer( + accelerator="cpu", + devices=1, + max_epochs=max_epochs, + callbacks=list(callbacks), + default_root_dir=tmp_path, + logger=False, + enable_checkpointing=False, + enable_progress_bar=False, + enable_model_summary=False, + ) + + def snapshot(model): + prefixes = ("backbone.teacher.", "projection_head.teacher.", "queue.") + return { + name: value.detach().clone() + for name, value in model.state_dict().items() + if name.startswith(prefixes) + } + + model = make_model() + initial = snapshot(model) + trainer = make_trainer(max_epochs=1) + manager = spt.Manager(trainer=trainer, module=model, data=make_data(), seed=0) + manager() + assert trainer.global_step == 2 + + trained = snapshot(model) + assert not torch.equal( + trained["backbone.teacher.1.weight"], initial["backbone.teacher.1.weight"] + ) + assert trained["backbone.teacher.2.num_batches_tracked"].item() == 2 + assert trained["queue.pointer"].item() == 8 + + checkpoint = tmp_path / "ressl.ckpt" + manager.save_checkpoint(str(checkpoint)) + + class CheckRestoredState(pl.Callback): + checked = False + + def on_train_start(self, trainer, pl_module): + assert trainer.global_step == 2 + torch.testing.assert_close(snapshot(pl_module), trained, rtol=0, atol=0) + self.checked = True + + check = CheckRestoredState() + resumed_trainer = make_trainer(max_epochs=2, callbacks=[check]) + spt.Manager( + trainer=resumed_trainer, + module=make_model(), + data=make_data(), + seed=0, + ckpt_path=str(checkpoint), + weights_only=False, + )() + + assert check.checked + assert resumed_trainer.global_step == 4 + + +def test_ressl_queue_append_and_state_dict_roundtrip(): + queue = UnsortedQueue(max_length=8, shape=4) + initial = F.normalize(torch.randn(8, 4), dim=-1) + queue.append(initial) + before = queue.get().detach().clone() + keys = F.normalize(torch.randn(2, 4), dim=-1) + queue.append(keys) + assert queue.get().shape == (8, 4) + assert not torch.equal(queue.get(), before) + + restored = UnsortedQueue(max_length=8, shape=4) + restored.load_state_dict(copy.deepcopy(queue.state_dict())) + torch.testing.assert_close(restored.get(), queue.get()) + for key, value in queue.state_dict().items(): + torch.testing.assert_close(restored.state_dict()[key], value) + + +def _distributed_queue_worker(rank: int, init_file: str) -> None: + dist.init_process_group( + backend="gloo", + init_method=f"file://{init_file}", + rank=rank, + world_size=2, + ) + try: + local = torch.tensor([[float(rank + 1), float(rank + 2)]]) + gathered = torch.cat(all_gather(local), dim=0) + expected = torch.tensor([[1.0, 2.0], [2.0, 3.0]]) + torch.testing.assert_close(gathered, expected) + + queue = UnsortedQueue(max_length=4, shape=2) + queue.append(torch.zeros(4, 2)) + queue.append(gathered) + contents = queue.get().detach().clone() + other = contents.clone() + dist.broadcast(other, src=0) + torch.testing.assert_close(contents, other) + + pointer = queue.state_dict()["pointer"].clone() + reference_pointer = pointer.clone() + dist.broadcast(reference_pointer, src=0) + torch.testing.assert_close(pointer, reference_pointer) + finally: + dist.destroy_process_group() + + +def test_ressl_loss_does_not_backprop_to_queue(): + loss_fn = ReSSLLoss() + + student = F.normalize(torch.randn(4, 8), dim=-1).detach().requires_grad_() + + teacher = F.normalize(torch.randn(4, 8), dim=-1) + + queue = F.normalize(torch.randn(16, 8), dim=-1).detach().requires_grad_() + + loss = loss_fn(student, teacher, queue) + loss.backward() + + assert student.grad is not None + assert queue.grad is None + + +@pytest.mark.skipif( + not dist.is_available() or os.name == "nt", + reason="Requires torch.distributed and POSIX file init", +) +def test_ressl_ddp_gather_and_synchronized_queue(): + # Use spawn, not fork, to match distributed test isolation. + with tempfile.TemporaryDirectory() as tmpdir: + init_file = os.path.join(tmpdir, "dist_init") + mp.spawn(_distributed_queue_worker, args=(init_file,), nprocs=2, join=True) diff --git a/stable_pretraining/tests/unit/test_split_batchnorm.py b/stable_pretraining/tests/unit/test_split_batchnorm.py new file mode 100644 index 000000000..4c873d792 --- /dev/null +++ b/stable_pretraining/tests/unit/test_split_batchnorm.py @@ -0,0 +1,48 @@ +"""Tests for split batch normalization.""" + +import pytest +import torch +from torch import nn + +from stable_pretraining.backbone import SplitBatchNorm + +pytestmark = pytest.mark.unit + + +def test_split_batchnorm_train_and_eval(): + x = torch.arange(32, dtype=torch.float32).reshape(4, 2, 2, 2) + x[1::2] = 2 * x[1::2] + 20 + layer = SplitBatchNorm(2, num_splits=2, momentum=0.25) + + references = [nn.BatchNorm2d(2, momentum=0.25) for _ in range(2)] + expected = torch.empty_like(x) + for split, reference in enumerate(references): + expected[split::2] = reference(x[split::2]) + + torch.testing.assert_close(layer(x), expected) + expected_mean = torch.stack([ref.running_mean for ref in references]).mean(0) + expected_var = torch.stack([ref.running_var for ref in references]).mean(0) + torch.testing.assert_close(layer.running_mean, expected_mean) + torch.testing.assert_close(layer.running_var, expected_var) + + # Evaluation accepts batches that cannot be evenly split. + layer.eval() + eval_x = x[:3] + expected_eval = nn.functional.batch_norm( + eval_x, expected_mean, expected_var, training=False, eps=layer.eps + ) + torch.testing.assert_close(layer(eval_x), expected_eval) + torch.testing.assert_close(layer.running_mean, expected_mean) + torch.testing.assert_close(layer.running_var, expected_var) + + +def test_split_batchnorm_rejects_nondivisible_training_batch(): + layer = SplitBatchNorm(2, num_splits=2) + with pytest.raises(ValueError, match="Batch size 3 must be divisible"): + layer(torch.zeros(3, 2, 2, 2)) + + +@pytest.mark.parametrize("num_splits", [0, -1, True, 1.5]) +def test_split_batchnorm_requires_positive_integer_splits(num_splits): + with pytest.raises(ValueError, match="num_splits must be a positive integer"): + SplitBatchNorm(2, num_splits=num_splits) diff --git a/stable_pretraining/utils/__init__.py b/stable_pretraining/utils/__init__.py index 58259ede8..970861c3a 100644 --- a/stable_pretraining/utils/__init__.py +++ b/stable_pretraining/utils/__init__.py @@ -44,6 +44,7 @@ dict_values, get_required_fn_parameters, ) + from .error_handling import with_hf_retry_ratelimit from .visualization import format_df_to_latex from . import flops, solver