From cb5f064507ce7f44d2c0aa77aa34a61379dbc6f3 Mon Sep 17 00:00:00 2001 From: ryan3473356866 <141656906+ryan3473356866@users.noreply.github.com> Date: Mon, 5 Oct 2026 18:14:07 -0400 Subject: [PATCH 1/5] Add Local Deep InfoMax (DIM) proposal document --- docs/proposals/dim.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 docs/proposals/dim.md diff --git a/docs/proposals/dim.md b/docs/proposals/dim.md new file mode 100644 index 000000000..d4b181722 --- /dev/null +++ b/docs/proposals/dim.md @@ -0,0 +1 @@ +# Local Deep InfoMax (DIM) From ae384f0711b0c06b3ed915e2a1f60ea3af6f1708 Mon Sep 17 00:00:00 2001 From: Yanbo Hua <3473356866@gmail.com> Date: Fri, 23 Oct 2026 13:10:15 -0400 Subject: [PATCH 2/5] [Feature] Local Deep InfoMax (JSD) with optional prior matching - Add LocalDIMLoss and DIMPriorLoss (stable_pretraining.losses) - Add LocalGlobalCritic and DIMEmbedding encode-and-dot-product critic (stable_pretraining.backbone) - Add local_dim forward function - Add CIFAR10 pretraining and frozen-encoder evaluation script (benchmarks/cifar10/local-dim-dcgan.py) - Add unit tests, METHODS.md and RELEASES.rst entries, API docs and citation --- METHODS.md | 3 + RELEASES.rst | 8 + benchmarks/cifar10/local-dim-dcgan.py | 278 +++++++++++++++ docs/proposals/dim.md | 1 - docs/source/api/backbone.rst | 2 + docs/source/api/forward.rst | 38 ++ docs/source/api/losses.rst | 2 + docs/source/references.bib | 10 + stable_pretraining/backbone/__init__.py | 3 + stable_pretraining/backbone/dim.py | 122 +++++++ stable_pretraining/forward.py | 112 ++++++ stable_pretraining/losses/__init__.py | 7 + stable_pretraining/losses/dim.py | 137 ++++++++ stable_pretraining/tests/unit/test_dim.py | 400 ++++++++++++++++++++++ 14 files changed, 1122 insertions(+), 1 deletion(-) create mode 100644 benchmarks/cifar10/local-dim-dcgan.py delete mode 100644 docs/proposals/dim.md create mode 100644 stable_pretraining/backbone/dim.py create mode 100644 stable_pretraining/losses/dim.py create mode 100644 stable_pretraining/tests/unit/test_dim.py diff --git a/METHODS.md b/METHODS.md index a8d123535..94963897f 100644 --- a/METHODS.md +++ b/METHODS.md @@ -18,6 +18,7 @@ Methods come in two forms: | Supervised | `supervised` | — | any | — | — | | SimCLR | `simclr` | `SimCLR` | `NTXEntLoss` | — | [Chen et al., 2020](https://arxiv.org/abs/2002.05709) | | BYOL | `byol` | `BYOL` | `BYOLLoss` | `TeacherStudent†` | [Grill et al., 2020](https://arxiv.org/abs/2006.07733) | +| Local DIM (JSD) | `local_dim` | — | `LocalDIMLoss`, `DIMPriorLoss` | — | [Hjelm et al., 2019](https://arxiv.org/abs/1808.06670) | | VICReg | `vicreg` | `VICReg` | `VICRegLoss` | — | [Bardes et al., 2022](https://arxiv.org/abs/2105.04906) | | 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) | @@ -112,5 +113,7 @@ All loss classes are importable from `stable_pretraining.losses`: | `DINOv2Loss` | DINOv2, DINOv3 | | `iBOTPatchLoss` | DINOv2, iBOT, MIMRefiner | | `MAELoss` | MAE | +| `LocalDIMLoss` | Local DIM | +| `DIMPriorLoss` | Local DIM (optional prior matching) | | `CLIPLoss` | Multimodal CLIP-style objectives | | `NegativeCosineSimilarity` | SimSiam, general use | diff --git a/RELEASES.rst b/RELEASES.rst index 9b10a58e6..916079f51 100644 --- a/RELEASES.rst +++ b/RELEASES.rst @@ -4,6 +4,14 @@ Unreleased **New method** +- Local Deep InfoMax (Hjelm et al., ICLR 2019) with the Jensen-Shannon + estimator: forward function ``stable_pretraining.forward.local_dim``, + losses ``LocalDIMLoss`` and ``DIMPriorLoss`` (optional adversarial prior + matching), and the encode-and-dot-product critic ``LocalGlobalCritic`` / + ``DIMEmbedding`` in ``stable_pretraining.backbone``. Only the local + objective is implemented (no global DIM). Registered in ``METHODS.md``, with + a CIFAR10 pretraining and frozen-encoder evaluation script under + ``benchmarks/cifar10/local-dim-dcgan.py``. - ``PMSN`` (Prior Matching for Siamese Networks): extends ``MSN`` by replacing its uniform-prior mean-entropy regulariser with a KL-divergence term against an arbitrary prior distribution over prototypes (power-law by default, diff --git a/benchmarks/cifar10/local-dim-dcgan.py b/benchmarks/cifar10/local-dim-dcgan.py new file mode 100644 index 000000000..ecf2cca32 --- /dev/null +++ b/benchmarks/cifar10/local-dim-dcgan.py @@ -0,0 +1,278 @@ +"""Local Deep InfoMax (JSD) on CIFAR10 with the DCGAN-style encoder of the paper. + +Pretrains the encoder with local DIM (plus the optional prior matching term), +then evaluates it as in Table 1 of Hjelm et al. (ICLR 2019): the encoder is +frozen and a one-hidden-layer classifier is trained on each of the ``conv``, +``fc`` and ``Y`` features. Settings not stated in the paper follow the +reference implementation (https://github.com/rdevon/DIM, ``basic32x32`` +config, cortex defaults): inputs normalized to [-1, 1] without augmentation, +Adam(lr=1e-4, betas=(0.5, 0.999)), batch size 64, 1000 epochs. Training +metrics are written by the ``Manager`` run registry (view them with ``spt web``). + +Usage:: + + python local-dim-dcgan.py # DIM(L): prior weight 0.1 + python local-dim-dcgan.py --prior-weight 0 # local-only ablation + python local-dim-dcgan.py --eval-only runs/local-dim/encoder.pt +""" + +import argparse +import json +import sys +from collections import OrderedDict +from pathlib import Path + +import lightning as pl +import torch +import torchmetrics +import torchvision +from lightning.pytorch.callbacks import LearningRateMonitor +from torch import nn + +import stable_pretraining as spt +from stable_pretraining import forward +from stable_pretraining.data import transforms + +sys.path.append(str(Path(__file__).parent.parent)) +from utils import get_data_dir + +MEAN_STD = {"mean": (0.5, 0.5, 0.5), "std": (0.5, 0.5, 0.5)} +LOCAL_LAYER = "layer1" +EVAL_LAYERS = {"conv": "layer2", "fc": "layer4"} +EVAL_DIMS = {"conv": 256 * 4 * 4, "fc": 1024, "Y": 64} +ADAM = {"lr": 1e-4, "betas": (0.5, 0.999)} # cortex defaults + + +def build_encoder(global_dim: int = 64) -> nn.Sequential: + """DCGAN-style encoder of the ``basic32x32`` config, layer names as in the reference.""" + + def conv(c_in, c_out): + return nn.Sequential( + nn.Conv2d(c_in, c_out, 4, 2, 1, bias=False), + nn.BatchNorm2d(c_out), + nn.ReLU(), + ) + + return nn.Sequential( + OrderedDict( + layer0=conv(3, 64), # 16x16 + layer1=conv(64, 128), # 8x8, local feature map + layer2=conv(128, 256), # 4x4, "conv" evaluation features + layer3=nn.Flatten(), + layer4=nn.Sequential( + nn.Linear(256 * 4 * 4, 1024, bias=False), + nn.BatchNorm1d(1024), + nn.ReLU(), + ), # "fc" evaluation features + layer5=nn.Linear(1024, global_dim), # global feature Y + ) + ) + + +def build_classifier(in_dim: int) -> nn.Sequential: + """Evaluation classifier of the reference ``ClassificationEval``. + + Linear(200) -> Dropout(0.1) -> BN -> ReLU -> Linear(10), in the layer order + of the reference ``Convnet`` blocks. + """ + return nn.Sequential( + nn.Flatten(), + nn.Linear(in_dim, 200), + nn.Dropout(0.1), + nn.BatchNorm1d(200), + nn.ReLU(), + nn.Linear(200, 10), + ) + + +def pretrain(args) -> nn.Module: + """Train the encoder with local DIM and return it.""" + data_dir = get_data_dir("cifar10") + transform = transforms.Compose(transforms.RGB(), transforms.ToImage(**MEAN_STD)) + train_dataset = spt.data.FromTorchDataset( + torchvision.datasets.CIFAR10(root=str(data_dir), train=True, download=True), + names=["image", "label"], + transform=transform, + ) + val_dataset = spt.data.FromTorchDataset( + torchvision.datasets.CIFAR10(root=str(data_dir), train=False, download=True), + names=["image", "label"], + transform=transform, + ) + data = spt.data.DataModule( + train=torch.utils.data.DataLoader( + train_dataset, + batch_size=args.batch_size, + num_workers=args.num_workers, + shuffle=True, + drop_last=True, + ), + val=torch.utils.data.DataLoader( + val_dataset, batch_size=256, num_workers=args.num_workers + ), + ) + + encoder = build_encoder() + module = spt.Module( + forward=forward.local_dim, + backbone=spt.backbone.HiddenStateExtractor( + encoder, [LOCAL_LAYER, *EVAL_LAYERS.values()] + ), + local_layer=LOCAL_LAYER, + dim_critic=spt.backbone.LocalGlobalCritic( + local_channels=128, global_dim=64, embed_dim=2048 + ), + dim_loss=spt.losses.LocalDIMLoss(), + prior_loss=spt.losses.DIMPriorLoss(spt.backbone.MLP(64, [1000, 200, 1])), + prior_weight=args.prior_weight, + optim={ + "optimizer": {"type": "Adam", **ADAM}, + "scheduler": {"type": "ConstantLR", "factor": 1.0}, + "interval": "epoch", + }, + hparams=vars(args), + ) + + # As with ``main.py local classifier`` in the reference code, classifiers on + # the conv / fc / Y features are trained alongside DIM for monitoring only; + # reported numbers come from evaluate(). + inputs = {**EVAL_LAYERS, "Y": "embedding"} + callbacks = [ + spt.callbacks.OnlineProbe( + module, + name=f"probe_{name}", + input=inputs[name], + target="label", + probe=build_classifier(dim), + loss=nn.CrossEntropyLoss(), + optimizer={"type": "Adam", **ADAM}, + metrics={"top1": torchmetrics.classification.MulticlassAccuracy(10)}, + ) + for name, dim in EVAL_DIMS.items() + ] + [ + LearningRateMonitor(logging_interval="epoch"), + ] + trainer = pl.Trainer( + max_epochs=args.epochs, + limit_train_batches=args.limit_train_batches, + num_sanity_val_steps=0, + callbacks=callbacks, + ) + spt.Manager(trainer=trainer, module=module, data=data)() + + torch.save(encoder.state_dict(), args.out_dir / "encoder.pt") + return encoder + + +@torch.no_grad() +def extract_features(encoder: nn.Module, train: bool, device) -> dict: + """Frozen ``conv``, ``fc`` and ``Y`` features and labels of a CIFAR10 split.""" + dataset = torchvision.datasets.CIFAR10( + root=str(get_data_dir("cifar10")), + train=train, + download=True, + transform=torchvision.transforms.Compose( + [ + torchvision.transforms.ToTensor(), + torchvision.transforms.Normalize(**MEAN_STD), + ] + ), + ) + loader = torch.utils.data.DataLoader(dataset, batch_size=500, num_workers=4) + extractor = spt.backbone.HiddenStateExtractor(encoder, list(EVAL_LAYERS.values())) + extractor.to(device).eval() + + feats = {name: [] for name in [*EVAL_LAYERS, "Y"]} + labels = [] + for images, targets in loader: + out = extractor(images.to(device)) + for name, layer in EVAL_LAYERS.items(): + feats[name].append(out.hidden_states[layer].flatten(1)) + feats["Y"].append(out.last_hidden_state) + labels.append(targets.to(device)) + extractor.remove_hooks() + return {k: torch.cat(v) for k, v in feats.items()}, torch.cat(labels) + + +def train_classifier(x_train, y_train, x_test, y_test, epochs, batch_size=64): + """Train the reference evaluation classifier; return per-epoch test accuracy. + + Matches ``ClassificationEval`` of the reference implementation: Adam(1e-4, + betas=(0.5, 0.999)), batch size 64, MultiStepLR(milestones=[50, 100], + gamma=0.1). + """ + classifier = build_classifier(x_train.size(1)).to(x_train.device) + optimizer = torch.optim.Adam(classifier.parameters(), **ADAM) + scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, [50, 100], gamma=0.1) + + accuracies = [] + for _ in range(epochs): + # cortex steps the scheduler at the start of every training epoch. + scheduler.step() + classifier.train() + for idx in torch.randperm(len(x_train), device=x_train.device).split( + batch_size + ): + loss = nn.functional.cross_entropy(classifier(x_train[idx]), y_train[idx]) + optimizer.zero_grad(set_to_none=True) + loss.backward() + optimizer.step() + + classifier.eval() + with torch.no_grad(): + preds = torch.cat([classifier(x).argmax(1) for x in x_test.split(1000)]) + accuracies.append((preds == y_test).float().mean().item() * 100) + return accuracies + + +def evaluate(encoder: nn.Module, args) -> dict: + """Table 1 protocol: test accuracy averaged over the last 100 classifier epochs.""" + device = "cuda" if torch.cuda.is_available() else "cpu" + train_feats, train_labels = extract_features(encoder, train=True, device=device) + test_feats, test_labels = extract_features(encoder, train=False, device=device) + + results = {} + for name in train_feats: + accuracies = train_classifier( + train_feats[name], + train_labels, + test_feats[name], + test_labels, + epochs=args.eval_epochs, + ) + last = accuracies[-min(100, len(accuracies)) :] + results[name] = { + "mean_last_100": sum(last) / len(last), + "final": accuracies[-1], + "best": max(accuracies), + } + print(f"{name:>4}: {results[name]}") + + with open(args.out_dir / "eval.json", "w") as f: + json.dump({"args": {k: str(v) for k, v in vars(args).items()}, **results}, f) + return results + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--prior-weight", type=float, default=0.1) + parser.add_argument("--epochs", type=int, default=1000) + parser.add_argument("--eval-epochs", type=int, default=1000) + parser.add_argument("--batch-size", type=int, default=64) + parser.add_argument("--num-workers", type=int, default=8) + parser.add_argument("--limit-train-batches", type=float, default=1.0) + parser.add_argument("--out-dir", type=Path, default=Path("runs/local-dim")) + parser.add_argument("--eval-only", type=Path, default=None) + args = parser.parse_args() + args.out_dir.mkdir(parents=True, exist_ok=True) + + if args.eval_only is None: + encoder = pretrain(args) + else: + encoder = build_encoder() + encoder.load_state_dict(torch.load(args.eval_only, map_location="cpu")) + evaluate(encoder, args) + + +if __name__ == "__main__": + main() diff --git a/docs/proposals/dim.md b/docs/proposals/dim.md deleted file mode 100644 index d4b181722..000000000 --- a/docs/proposals/dim.md +++ /dev/null @@ -1 +0,0 @@ -# Local Deep InfoMax (DIM) diff --git a/docs/source/api/backbone.rst b/docs/source/api/backbone.rst index 694c4110a..67312f699 100644 --- a/docs/source/api/backbone.rst +++ b/docs/source/api/backbone.rst @@ -37,3 +37,5 @@ Specialized Modules TeacherStudentWrapper EvalOnly + DIMEmbedding + LocalGlobalCritic diff --git a/docs/source/api/forward.rst b/docs/source/api/forward.rst index accbccd09..9d18fc01d 100644 --- a/docs/source/api/forward.rst +++ b/docs/source/api/forward.rst @@ -275,6 +275,44 @@ Supervised in_features: 2048 out_features: 1000 +Local DIM +~~~~~~~~~ + +.. autofunction:: local_dim + +**Required Module Attributes:** + +- ``backbone``: ``HiddenStateExtractor`` wrapping the encoder +- ``local_layer``: Name of the hooked layer providing the local feature map +- ``dim_critic``: Critic scoring global/local pairs (``LocalGlobalCritic``) +- ``dim_loss``: ``LocalDIMLoss`` +- ``prior_loss`` / ``prior_weight`` (optional): ``DIMPriorLoss`` and its weight + +**Key Features:** + +- Single view per image, no data augmentation required +- Jensen-Shannon mutual information between the global feature and every local feature +- Optional adversarial matching of the global feature to a uniform prior +- Only the local objective of Deep InfoMax; the global objective is not implemented + +**Example Config:** + +.. code-block:: yaml + + module: + forward: stable_pretraining.forward.local_dim + backbone: + _target_: stable_pretraining.backbone.HiddenStateExtractor + backbone: ... + module_names: [layer1] + local_layer: layer1 + dim_critic: + _target_: stable_pretraining.backbone.LocalGlobalCritic + local_channels: 128 + global_dim: 64 + dim_loss: + _target_: stable_pretraining.losses.LocalDIMLoss + Custom Forward Functions ------------------------ diff --git a/docs/source/api/losses.rst b/docs/source/api/losses.rst index 0b487a840..c355b29eb 100644 --- a/docs/source/api/losses.rst +++ b/docs/source/api/losses.rst @@ -12,3 +12,5 @@ stable_pretraining.losses NegativeCosineSimilarity VICRegLoss BarlowTwinsLoss + LocalDIMLoss + DIMPriorLoss diff --git a/docs/source/references.bib b/docs/source/references.bib index 60a02f87a..a8b8d9c6d 100644 --- a/docs/source/references.bib +++ b/docs/source/references.bib @@ -7,6 +7,16 @@ @inproceedings{chen2020simple organization={PMLR} } +@misc{hjelm2019learningdeeprepresentationsmutual, + title={Learning deep representations by mutual information estimation and maximization}, + author={R Devon Hjelm and Alex Fedorov and Samuel Lavoie-Marchildon and Karan Grewal and Phil Bachman and Adam Trischler and Yoshua Bengio}, + year={2019}, + eprint={1808.06670}, + archivePrefix={arXiv}, + primaryClass={stat.ML}, + url={https://arxiv.org/abs/1808.06670}, +} + @article{grill2020bootstrap, title={Bootstrap your own latent-a new approach to self-supervised learning}, author={Grill, Jean-Bastien and Strub, Florian and Altch{\'e}, Florent and Tallec, Corentin and Richemond, Pierre and Buchatskaya, Elena and Doersch, Carl and Avila Pires, Bernardo and Guo, Zhaohan and Gheshlaghi Azar, Mohammad and others}, diff --git a/stable_pretraining/backbone/__init__.py b/stable_pretraining/backbone/__init__.py index 4f375c916..96352d8b0 100644 --- a/stable_pretraining/backbone/__init__.py +++ b/stable_pretraining/backbone/__init__.py @@ -1,4 +1,5 @@ from .convmixer import ConvMixer +from .dim import DIMEmbedding, LocalGlobalCritic from .jet import Jet from .mlp import MLP from .nn_modules import ( @@ -93,6 +94,8 @@ FeaturesConcat, set_embedding_dim, ConvMixer, + DIMEmbedding, + LocalGlobalCritic, vit_hf, MultiHeadAttentiveProbe, LinearProbe, diff --git a/stable_pretraining/backbone/dim.py b/stable_pretraining/backbone/dim.py new file mode 100644 index 000000000..2d5f16c06 --- /dev/null +++ b/stable_pretraining/backbone/dim.py @@ -0,0 +1,122 @@ +"""Critic networks for Deep InfoMax (DIM) :cite:`hjelm2019learning`.""" + +import torch +import torch.nn as nn + + +class DIMEmbedding(nn.Module): + """Residual 1x1-convolution embedding used by the DIM encode-and-dot-product critic. + + Maps every location of a ``[B, C, H, W]`` feature map to an + ``out_channels``-dimensional vector with a non-linear branch + (``1x1 conv -> BN -> ReLU -> 1x1 conv``) plus a linear 1x1 shortcut, + followed by LayerNorm over channels. A global feature vector is embedded + by treating it as a ``[B, C, 1, 1]`` map. + + Args: + in_channels: Number of input channels. + out_channels: Embedding dimension. + + Note: + Mirrors ``MI1x1ConvNet`` from the reference implementation + (https://github.com/rdevon/DIM). When ``out_channels >= in_channels`` + the shortcut is initialized close to an identity map, so the + embedding initially preserves the input features. + """ + + def __init__(self, in_channels: int, out_channels: int): + super().__init__() + self.block_nonlinear = nn.Sequential( + nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False), + nn.BatchNorm2d(out_channels), + nn.ReLU(), + nn.Conv2d(out_channels, out_channels, kernel_size=1), + ) + self.linear_shortcut = nn.Conv2d( + in_channels, out_channels, kernel_size=1, bias=False + ) + self.layer_norm = nn.LayerNorm(out_channels) + + if out_channels >= in_channels: + with torch.no_grad(): + weight = self.linear_shortcut.weight + weight.uniform_(-0.01, 0.01) + idx = torch.arange(in_channels) + weight[idx, idx, 0, 0] = 1.0 + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Embed every location of a feature map. + + Args: + x: Feature map of shape ``[B, in_channels, H, W]``. + + Returns: + torch.Tensor: Embeddings of shape ``[B, out_channels, H, W]``. + """ + h = self.block_nonlinear(x) + self.linear_shortcut(x) + return self.layer_norm(h.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) + + +class LocalGlobalCritic(nn.Module): + """Encode-and-dot-product critic scoring global/local feature pairs for local DIM. + + The global feature of each image and every location of each local + feature map are embedded into a shared space by two :class:`DIMEmbedding` + networks; the score of a pair is the dot product of their embeddings. + All ``B x B x (H * W)`` pairs of a batch are scored at once, which is the + input expected by :class:`~stable_pretraining.losses.LocalDIMLoss`. + + Args: + local_channels: Channels ``C`` of the local feature map. + global_dim: Dimension ``G`` of the global feature vector. + embed_dim: Dimension of the shared embedding space. Defaults to 2048, + as in the reference implementation. When it equals ``global_dim`` + the global feature is used as is, as in the reference + implementation. + + Example: + :: + + critic = LocalGlobalCritic(local_channels=128, global_dim=64) + scores = critic(feature_map, global_features) # [B, B, H * W] + """ + + def __init__(self, local_channels: int, global_dim: int, embed_dim: int = 2048): + super().__init__() + self.local_net = DIMEmbedding(local_channels, embed_dim) + if global_dim == embed_dim: + self.global_net = nn.Identity() + else: + self.global_net = DIMEmbedding(global_dim, embed_dim) + + def forward( + self, local_features: torch.Tensor, global_features: torch.Tensor + ) -> torch.Tensor: + """Score every (global, local location) pair in the batch. + + Args: + local_features: Local feature map of shape ``[B, C, H, W]``. + global_features: Global features of shape ``[B, G]``. + + Returns: + torch.Tensor: Scores of shape ``[B, B, H * W]`` where + ``scores[a, b, i]`` compares the global feature of image ``a`` + with location ``i`` of the local feature map of image ``b``. + + Raises: + ValueError: If the inputs are not ``[B, C, H, W]`` and ``[B, G]`` + with the same batch size. + """ + if local_features.ndim != 4 or global_features.ndim != 2: + raise ValueError( + "expected local_features [B, C, H, W] and global_features [B, G], " + f"got {tuple(local_features.shape)} and {tuple(global_features.shape)}" + ) + if local_features.size(0) != global_features.size(0): + raise ValueError( + "local_features and global_features must share the batch size, " + f"got {local_features.size(0)} and {global_features.size(0)}" + ) + local_emb = self.local_net(local_features).flatten(2) + global_emb = self.global_net(global_features[:, :, None, None]).flatten(1) + return torch.einsum("ad,bdi->abi", global_emb, local_emb) diff --git a/stable_pretraining/forward.py b/stable_pretraining/forward.py index f33f09241..e359d100b 100644 --- a/stable_pretraining/forward.py +++ b/stable_pretraining/forward.py @@ -14,6 +14,7 @@ - ``nnclr`` — NNCLR nearest-neighbor contrastive learning - ``dino`` — DINO self-distillation with multi-crop - ``dinov2`` — DINOv2 with iBOT masked patch prediction + - ``local_dim`` — local Deep InfoMax (JSD estimator, optional prior) These are the lightweight composable form of each method. For full ``LightningModule`` implementations of 30+ SSL methods (BYOL, DINO, MAE, @@ -1261,3 +1262,114 @@ def dinov2(self, batch: dict[str, Any], stage: str) -> dict[str, torch.Tensor]: ) return out + + +def local_dim(self, batch: dict[str, Any], stage: str) -> dict[str, torch.Tensor]: + """Forward function for local Deep InfoMax (DIM). + + Local DIM maximizes a Jensen-Shannon estimate of the mutual information + between the global feature of an image and every location of an + intermediate feature map of the same image. Negatives pair the global + feature with feature maps of the other images in the batch, so a single + un-augmented view per image is enough. An adversarial term can + optionally match the global feature to a uniform prior. + + Args: + self: Module instance (automatically bound) with required attributes: + - backbone: ``HiddenStateExtractor`` wrapping the encoder + - local_layer: Name of the hooked layer giving the local feature map + - dim_critic: Critic scoring global/local pairs (``LocalGlobalCritic``) + - dim_loss: Local DIM loss (``LocalDIMLoss``) + - prior_loss (optional): Prior matching loss (``DIMPriorLoss``) + - prior_weight (optional): Prior weight ``gamma`` (default 0: no prior) + batch: Input batch dictionary containing: + - 'image': Tensor of images [N, C, H, W] + - 'label': Labels [N] (optional, passed through for callbacks) + stage: Training stage ('train', 'val', or 'test') + + Returns: + Dictionary containing: + - 'embedding': Global features from the backbone + - each hooked layer name: its captured hidden state (for probes) + - 'loss': Local DIM loss plus prior terms (during training only) + - 'label': Labels if present (for probes/callbacks) + + Note: + Introduced in the Deep InfoMax paper :cite:`hjelm2019learning`. Only + the local objective (and optional prior) is implemented; the global + DIM objective is not. The discriminator loss of the prior term is + added to ``loss`` with weight 1, as in the reference implementation; + it never reaches the encoder. + + Example: + :: + + import torch + import stable_pretraining as spt + from stable_pretraining.forward import local_dim + + backbone = spt.backbone.HiddenStateExtractor(encoder, ["layer1"]) + module = spt.Module( + forward=local_dim, + backbone=backbone, + local_layer="layer1", + dim_critic=spt.backbone.LocalGlobalCritic(128, 64), + dim_loss=spt.losses.LocalDIMLoss(), + prior_loss=spt.losses.DIMPriorLoss( + spt.backbone.MLP(64, [1000, 200, 1]) + ), + prior_weight=0.1, + optim={ + "optimizer": {"type": "Adam", "lr": 1e-4, "betas": (0.5, 0.999)} + }, + ) + """ + features = self.backbone(batch["image"]) + out = dict(features.hidden_states) + out["embedding"] = features.last_hidden_state + if "label" in batch: + out["label"] = batch["label"] + + if self.training: + local_features = features.hidden_states[self.local_layer] + local_loss = self.dim_loss(self.dim_critic(local_features, out["embedding"])) + out["loss"] = local_loss + + prior_weight = getattr(self, "prior_weight", 0.0) + if prior_weight > 0: + prior = self.prior_loss(out["embedding"]) + out["loss"] = ( + out["loss"] + prior_weight * prior["encoder"] + prior["discriminator"] + ) + self.log( + f"{stage}/prior_encoder_loss", + prior["encoder"], + on_step=True, + on_epoch=True, + sync_dist=True, + ) + self.log( + f"{stage}/prior_discriminator_loss", + prior["discriminator"], + on_step=True, + on_epoch=True, + sync_dist=True, + ) + + self.log( + f"{stage}/local_dim_loss", + local_loss, + on_step=True, + on_epoch=True, + sync_dist=True, + ) + self.log( + f"{stage}/loss", + out["loss"], + on_step=True, + on_epoch=True, + sync_dist=True, + prog_bar=True, + ) + + return out diff --git a/stable_pretraining/losses/__init__.py b/stable_pretraining/losses/__init__.py index 37eff8da9..b4dc2633f 100644 --- a/stable_pretraining/losses/__init__.py +++ b/stable_pretraining/losses/__init__.py @@ -2,6 +2,7 @@ This module provides various self-supervised learning loss functions organized by category: - DINO losses: Self-distillation methods (DINOLoss, iBOTPatchLoss) +- Deep InfoMax losses: Local mutual information maximization (LocalDIMLoss, DIMPriorLoss) - Joint embedding losses: Contrastive and non-contrastive methods (BYOL, VICReg, Barlow Twins, SimCLR) - Reconstruction losses: Masked prediction methods (MAE) - Utilities: Helper functions (sinkhorn_knopp, off_diagonal, NegativeCosineSimilarity) @@ -10,6 +11,9 @@ # DINO self-distillation losses from .dino import DINOv1Loss, DINOv2Loss, iBOTPatchLoss +# Deep InfoMax losses +from .dim import DIMPriorLoss, LocalDIMLoss + # Joint embedding losses from .joint_embedding import ( BYOLLoss, @@ -38,6 +42,9 @@ "DINOv1Loss", "DINOv2Loss", "iBOTPatchLoss", + # Deep InfoMax + "DIMPriorLoss", + "LocalDIMLoss", # Joint embedding "BYOLLoss", "VICRegLoss", diff --git a/stable_pretraining/losses/dim.py b/stable_pretraining/losses/dim.py new file mode 100644 index 000000000..41572b319 --- /dev/null +++ b/stable_pretraining/losses/dim.py @@ -0,0 +1,137 @@ +"""Deep InfoMax (DIM) losses. + +This module contains the objectives of local Deep InfoMax +:cite:`hjelm2019learning`: a Jensen-Shannon mutual information estimator +between a global feature vector and every location of a local feature map, +and the optional adversarial prior matching term on the global feature. +""" + +import math + +import torch +import torch.nn.functional as F +from torch.func import functional_call + + +class LocalDIMLoss(torch.nn.Module): + """Jensen-Shannon local DIM objective :cite:`hjelm2019learning`. + + Takes a tensor of critic scores ``scores[a, b, i]`` comparing the global + feature of image ``a`` with location ``i`` of the local feature map of + image ``b``. Diagonal pairs (``a == b``) are positives (samples from the + joint distribution); off-diagonal pairs are negatives (samples from the + product of marginals). The loss is the negated JSD mutual information + estimator (Eq. 4 of the paper) averaged over all locations (Eq. 6). + + Note: + Positives and negatives are averaged separately, as in the reference + implementation, so the ``B`` positives per location are not drowned + out by the ``B * (B - 1)`` negatives. The ``log 2`` shifts of the + reference implementation are kept so that ``-loss`` matches its logged + JSD estimate and lies in ``(-inf, 2 log 2]``. Negatives are drawn from + the local batch only; no cross-device gathering is performed. + """ + + def forward(self, scores: torch.Tensor) -> torch.Tensor: + """Compute the local DIM loss. + + Args: + scores: Critic scores of shape ``[B, B, M]`` where ``B`` is the + batch size and ``M`` the number of local feature locations. + + Returns: + torch.Tensor: Scalar loss value. + + Raises: + ValueError: If ``scores`` is not ``[B, B, M]`` or ``B < 2`` (no + negative pairs). + """ + if scores.ndim != 3 or scores.size(0) != scores.size(1): + raise ValueError( + f"scores must have shape [B, B, M], got {tuple(scores.shape)}" + ) + batch_size = scores.size(0) + if batch_size < 2: + raise ValueError("LocalDIMLoss needs a batch size >= 2 to form negatives") + + pos_mask = torch.eye(batch_size, dtype=torch.bool, device=scores.device) + log_2 = math.log(2.0) + e_pos = log_2 - F.softplus(-scores[pos_mask]).mean() + e_neg = F.softplus(scores[~pos_mask]).mean() - log_2 + return e_neg - e_pos + + +class DIMPriorLoss(torch.nn.Module): + """Adversarial prior matching term of DIM :cite:`hjelm2019learning`. + + A discriminator learns to tell samples of a uniform prior on ``[0, 1]^D`` + from ``sigmoid(embedding)``, while the encoder is trained to fool it + (Eq. 7 of the paper). Both terms are returned so they can be added to a + single loss and optimized with one backward pass: the discriminator term + only reaches the discriminator parameters and the encoder term only + reaches the embedding. + + Args: + discriminator: Network mapping ``[N, D]`` to ``[N, 1]`` logits, e.g. + ``spt.backbone.MLP(D, [1000, 200, 1])`` as in the paper (Table 10). + gradient_penalty: Weight of the gradient penalty on the + discriminator. ``0`` disables it. + + Note: + Details not stated in the paper follow the reference implementation + (https://github.com/rdevon/DIM): the embedding is squashed with a + sigmoid before being compared to the prior, the discriminator uses the + standard GAN loss, the encoder uses the non-saturating generator loss, + and the discriminator is regularized with the gradient penalty of + Mescheder et al. (2018), averaged over the prior and encoder samples. + The penalty reproduces the reference ``contrastive_gradient_penalty`` + exactly, including its indexing of the discriminator output with + ``[-1]``: only the input gradient of the last sample of the batch is + non-zero, and its squared norm is divided by the batch size. + """ + + def __init__(self, discriminator: torch.nn.Module, gradient_penalty: float = 1.0): + super().__init__() + self.discriminator = discriminator + self.gradient_penalty = gradient_penalty + + def _penalty(self, samples: torch.Tensor) -> torch.Tensor: + samples = samples.detach().requires_grad_(True) + with torch.enable_grad(): + score = self.discriminator(samples)[-1] + (grad,) = torch.autograd.grad(score.sum(), samples, create_graph=True) + return grad.pow(2).flatten(1).sum(dim=1).mean() + + def forward(self, embedding: torch.Tensor) -> dict[str, torch.Tensor]: + """Compute the prior matching terms. + + Args: + embedding: Global features of shape ``[N, D]`` (before sigmoid). + + Returns: + dict[str, torch.Tensor]: ``"encoder"``, the generator loss whose + gradient only reaches ``embedding``, and ``"discriminator"``, the + discriminator loss (including the gradient penalty) whose gradient + only reaches the discriminator parameters. + """ + fake = torch.sigmoid(embedding) + real = torch.rand_like(fake) + + disc_loss = ( + F.softplus(-self.discriminator(real)).mean() + + F.softplus(self.discriminator(fake.detach())).mean() + ) + if self.gradient_penalty > 0: + penalty = 0.5 * (self._penalty(real) + self._penalty(fake)) + disc_loss = disc_loss + self.gradient_penalty * penalty + + # Frozen copy of the discriminator so that the encoder term does not + # train the discriminator to be fooled. + frozen = { + name: tensor.detach() + for name, tensor in self.discriminator.state_dict(keep_vars=True).items() + } + enc_loss = F.softplus( + -functional_call(self.discriminator, frozen, (fake,)) + ).mean() + return {"encoder": enc_loss, "discriminator": disc_loss} diff --git a/stable_pretraining/tests/unit/test_dim.py b/stable_pretraining/tests/unit/test_dim.py new file mode 100644 index 000000000..fc8b1820e --- /dev/null +++ b/stable_pretraining/tests/unit/test_dim.py @@ -0,0 +1,400 @@ +"""Unit tests for the Deep InfoMax (DIM) components.""" + +import math +from collections import OrderedDict +from unittest.mock import Mock + +import pytest +import torch +import torch.nn as nn +import torch.nn.functional as F + +import stable_pretraining as spt +from stable_pretraining.backbone import DIMEmbedding, LocalGlobalCritic +from stable_pretraining.forward import local_dim +from stable_pretraining.losses import DIMPriorLoss, LocalDIMLoss + +LOG_2 = math.log(2.0) + + +def _reference_fenchel_dual_jsd(l_enc: torch.Tensor, m_enc: torch.Tensor): + """Port of ``fenchel_dual_loss(l, m, measure="JSD")`` from rdevon/DIM. + + ``l_enc`` is ``[N, units, n_locals]`` and ``m_enc`` is ``[N, units, 1]``. + """ + n, units, n_locals = l_enc.size() + l_flat = l_enc.permute(0, 2, 1).reshape(-1, units) + m_flat = m_enc.permute(0, 2, 1).reshape(-1, units) + u = torch.mm(m_flat, l_flat.t()).reshape(n, 1, n, n_locals).permute(0, 2, 3, 1) + mask = torch.eye(n) + e_pos = (LOG_2 - F.softplus(-u)).mean(2).mean(2) + e_neg = (F.softplus(-u) + u - LOG_2).mean(2).mean(2) + e_pos = (e_pos * mask).sum() / mask.sum() + e_neg = (e_neg * (1 - mask)).sum() / (1 - mask).sum() + return e_neg - e_pos + + +@pytest.mark.unit +class TestLocalDIMLoss: + """Unit tests for :class:`LocalDIMLoss`.""" + + def test_matches_reference_implementation(self): + """Scores built as global-local dot products reproduce the author's loss.""" + torch.manual_seed(0) + batch_size, units, n_locals = 5, 16, 9 + l_enc = torch.randn(batch_size, units, n_locals) + m_enc = torch.randn(batch_size, units, 1) + scores = torch.einsum("ad,bdi->abi", m_enc.squeeze(-1), l_enc) + + loss = LocalDIMLoss()(scores) + + expected = _reference_fenchel_dual_jsd(l_enc, m_enc) + assert torch.allclose(loss, expected, atol=1e-6) + + def test_matches_closed_form(self): + """Loss equals mean softplus over negatives plus over negated positives.""" + torch.manual_seed(1) + scores = torch.randn(4, 4, 3) + eye = torch.eye(4, dtype=torch.bool) + + loss = LocalDIMLoss()(scores) + + expected = ( + F.softplus(-scores[eye]).mean() + + F.softplus(scores[~eye]).mean() + - 2 * LOG_2 + ) + assert loss.ndim == 0 + assert torch.allclose(loss, expected, atol=1e-6) + + def test_uninformative_critic_gives_zero(self): + """A critic scoring every pair 0 cannot separate them: the estimate is 0.""" + loss = LocalDIMLoss()(torch.zeros(3, 3, 4)) + assert torch.allclose(loss, torch.tensor(0.0), atol=1e-7) + + def test_perfect_critic_reaches_lower_bound(self): + """Confident, correct scores drive the loss to its minimum ``-2 log 2``.""" + batch_size = 4 + eye = torch.eye(batch_size).unsqueeze(-1).expand(-1, -1, 6) + scores = 50.0 * (2 * eye - 1) + + loss = LocalDIMLoss()(scores) + + assert torch.allclose(loss, torch.tensor(-2 * LOG_2), atol=1e-6) + + def test_estimate_is_bounded(self): + """``-loss`` never exceeds ``2 log 2`` regardless of the scores.""" + torch.manual_seed(2) + for scale in (0.1, 1.0, 100.0): + loss = LocalDIMLoss()(scale * torch.randn(6, 6, 5)) + assert -loss.item() <= 2 * LOG_2 + 1e-6 + + def test_gradient_direction(self): + """Gradient descent raises positive scores and lowers negative ones.""" + scores = torch.zeros(3, 3, 2, requires_grad=True) + LocalDIMLoss()(scores).backward() + + eye = torch.eye(3, dtype=torch.bool) + assert (scores.grad[eye] < 0).all() + assert (scores.grad[~eye] > 0).all() + + @pytest.mark.parametrize("shape", [(4, 4), (4, 3, 2), (4, 4, 2, 1)]) + def test_rejects_bad_shape(self, shape): + """Scores must be a square-batch ``[B, B, M]`` tensor.""" + with pytest.raises(ValueError, match=r"\[B, B, M\]"): + LocalDIMLoss()(torch.zeros(shape)) + + def test_rejects_single_sample_batch(self): + """A batch of one has no negative pairs.""" + with pytest.raises(ValueError, match="batch size >= 2"): + LocalDIMLoss()(torch.zeros(1, 1, 4)) + + +@pytest.mark.unit +class TestDIMEmbedding: + """Unit tests for :class:`DIMEmbedding`.""" + + def test_output_shape(self): + """Every location is embedded independently: spatial size is kept.""" + emb = DIMEmbedding(in_channels=8, out_channels=32) + out = emb(torch.randn(4, 8, 5, 5)) + assert out.shape == (4, 32, 5, 5) + + def test_output_is_layer_normalized(self): + """Each location's embedding has zero mean and unit variance over channels.""" + torch.manual_seed(0) + emb = DIMEmbedding(in_channels=8, out_channels=32) + out = emb(torch.randn(4, 8, 3, 3)) + assert torch.allclose(out.mean(dim=1), torch.zeros(4, 3, 3), atol=1e-5) + assert torch.allclose( + out.var(dim=1, unbiased=False), torch.ones(4, 3, 3), atol=1e-3 + ) + + def test_shortcut_initialized_near_identity(self): + """With ``out >= in`` the shortcut starts as an identity plus small noise.""" + emb = DIMEmbedding(in_channels=4, out_channels=6) + weight = emb.linear_shortcut.weight[:, :, 0, 0] + eye = torch.eye(6, 4, dtype=torch.bool) + assert torch.equal(weight[eye], torch.ones(4)) + assert weight[~eye].abs().max() <= 0.01 + + def test_shortcut_default_init_when_compressing(self): + """With ``out < in`` no identity exists, so the default init is kept.""" + emb = DIMEmbedding(in_channels=6, out_channels=4) + diag = torch.diagonal(emb.linear_shortcut.weight[:, :, 0, 0]) + assert not torch.equal(diag, torch.ones(4)) + + +@pytest.mark.unit +class TestLocalGlobalCritic: + """Unit tests for :class:`LocalGlobalCritic`.""" + + @staticmethod + def _inputs(batch_size=4, channels=8, size=3, global_dim=5, seed=0): + g = torch.Generator().manual_seed(seed) + local = torch.randn(batch_size, channels, size, size, generator=g) + glob = torch.randn(batch_size, global_dim, generator=g) + return local, glob + + def test_output_shape(self): + """All global/local-location pairs of the batch are scored.""" + critic = LocalGlobalCritic(local_channels=8, global_dim=5, embed_dim=16) + local, glob = self._inputs() + assert critic(local, glob).shape == (4, 4, 9) + + def test_scores_are_embedding_dot_products(self): + """``scores[a, b, i]`` is the dot product of the two embeddings.""" + critic = LocalGlobalCritic(local_channels=8, global_dim=5, embed_dim=16) + local, glob = self._inputs() + + scores = critic(local, glob) + + local_emb = critic.local_net(local).flatten(2) + global_emb = critic.global_net(glob[:, :, None, None]).flatten(1) + a, b, i = 1, 3, 7 + expected = torch.dot(global_emb[a], local_emb[b, :, i]) + assert torch.allclose(scores[a, b, i], expected, atol=1e-5) + + def test_global_feature_used_as_is_when_dims_match(self): + """As in the reference, no global embedding is learned if ``G == embed_dim``.""" + critic = LocalGlobalCritic(local_channels=8, global_dim=16, embed_dim=16) + local, glob = self._inputs(global_dim=16) + + scores = critic(local, glob) + + assert isinstance(critic.global_net, nn.Identity) + local_emb = critic.local_net(local).flatten(2) + assert torch.allclose(scores[0, 1, 2], torch.dot(glob[0], local_emb[1, :, 2])) + + def test_axes_follow_global_then_local(self): + """Changing image ``b``'s local map only changes column ``b`` of the scores. + + In eval mode BatchNorm uses running statistics, so samples do not + interact and the effect of each input is isolated. + """ + critic = LocalGlobalCritic(local_channels=8, global_dim=5, embed_dim=16).eval() + local, glob = self._inputs() + base = critic(local, glob) + + local_changed = local.clone() + local_changed[2] += 1.0 + diff = (critic(local_changed, glob) - base).abs().sum(dim=-1) + assert diff[:, 2].gt(0).all() + assert diff[:, [0, 1, 3]].eq(0).all() + + glob_changed = glob.clone() + glob_changed[1] += 1.0 + diff = (critic(local, glob_changed) - base).abs().sum(dim=-1) + assert diff[1].gt(0).all() + assert diff[[0, 2, 3]].eq(0).all() + + def test_trains_with_local_dim_loss(self): + """The loss backpropagates into both embedding networks and the features.""" + critic = LocalGlobalCritic(local_channels=8, global_dim=5, embed_dim=16) + local, glob = self._inputs() + local.requires_grad_(True) + glob.requires_grad_(True) + + loss = LocalDIMLoss()(critic(local, glob)) + loss.backward() + + assert torch.isfinite(loss) + for net in (critic.local_net, critic.global_net): + assert any( + p.grad is not None and p.grad.abs().sum() > 0 for p in net.parameters() + ) + assert local.grad.abs().sum() > 0 + assert glob.grad.abs().sum() > 0 + + @pytest.mark.parametrize( + "local_shape,global_shape", + [((4, 8, 9), (4, 5)), ((4, 8, 3, 3), (4, 5, 1)), ((4, 8, 3, 3), (3, 5))], + ) + def test_rejects_bad_inputs(self, local_shape, global_shape): + """Inputs must be ``[B, C, H, W]`` and ``[B, G]`` with matching ``B``.""" + critic = LocalGlobalCritic(local_channels=8, global_dim=5, embed_dim=16) + with pytest.raises(ValueError): + critic(torch.randn(local_shape), torch.randn(global_shape)) + + +@pytest.mark.unit +class TestDIMPriorLoss: + """Unit tests for :class:`DIMPriorLoss`.""" + + @staticmethod + def _grad_norm(module: nn.Module) -> float: + return sum( + p.grad.abs().sum().item() for p in module.parameters() if p.grad is not None + ) + + def test_returns_finite_scalars(self): + """Both terms are finite scalars.""" + prior = DIMPriorLoss(spt.backbone.MLP(6, [16, 8, 1])) + terms = prior(torch.randn(5, 6)) + assert set(terms) == {"encoder", "discriminator"} + for value in terms.values(): + assert value.ndim == 0 and torch.isfinite(value) + + def test_encoder_term_does_not_train_discriminator(self): + """The generator loss reaches the embedding but not the discriminator.""" + prior = DIMPriorLoss(spt.backbone.MLP(6, [16, 8, 1])) + embedding = torch.randn(5, 6, requires_grad=True) + + prior(embedding)["encoder"].backward() + + assert embedding.grad.abs().sum() > 0 + assert self._grad_norm(prior.discriminator) == 0 + + def test_discriminator_term_does_not_train_encoder(self): + """The discriminator loss and penalty never reach the embedding.""" + prior = DIMPriorLoss(spt.backbone.MLP(6, [16, 8, 1])) + embedding = torch.randn(5, 6, requires_grad=True) + + prior(embedding)["discriminator"].backward() + + assert embedding.grad is None + assert self._grad_norm(prior.discriminator) > 0 + + def test_matches_gan_losses(self): + """Terms equal the GAN discriminator and non-saturating generator losses.""" + disc = nn.Linear(4, 1) + prior = DIMPriorLoss(disc, gradient_penalty=0.0) + embedding = torch.randn(8, 4) + + torch.manual_seed(3) + terms = prior(embedding) + torch.manual_seed(3) + real = torch.rand(8, 4) + + fake = torch.sigmoid(embedding) + expected_disc = F.softplus(-disc(real)).mean() + F.softplus(disc(fake)).mean() + expected_enc = F.softplus(-disc(fake)).mean() + assert torch.allclose(terms["discriminator"], expected_disc, atol=1e-6) + assert torch.allclose(terms["encoder"], expected_enc, atol=1e-6) + + def test_gradient_penalty_matches_reference(self): + """Penalty follows the reference: only the last sample's gradient, divided by N. + + A linear discriminator has input gradient ``w``, so each of the two + penalties is ``|w|^2 / N`` and so is their average. + """ + disc = nn.Linear(4, 1) + embedding = torch.randn(8, 4) + + torch.manual_seed(0) + without = DIMPriorLoss(disc, gradient_penalty=0.0)(embedding)["discriminator"] + torch.manual_seed(0) + with_gp = DIMPriorLoss(disc, gradient_penalty=2.0)(embedding)["discriminator"] + + expected = 2.0 * disc.weight.pow(2).sum() / 8 + assert torch.allclose(with_gp - without, expected, atol=1e-6) + + +def _tiny_dim_module(prior_weight: float = 0.1) -> spt.Module: + """Build a small local DIM ``Module`` on 16x16 inputs.""" + encoder = nn.Sequential( + OrderedDict( + layer0=nn.Sequential( + nn.Conv2d(3, 8, 4, 2, 1, bias=False), nn.BatchNorm2d(8), nn.ReLU() + ), + layer1=nn.Sequential( + nn.Conv2d(8, 16, 4, 2, 1, bias=False), nn.BatchNorm2d(16), nn.ReLU() + ), + flatten=nn.Flatten(), + layer2=nn.Linear(16 * 4 * 4, 6), + ) + ) + module = spt.Module( + forward=local_dim, + backbone=spt.backbone.HiddenStateExtractor(encoder, ["layer1"]), + local_layer="layer1", + dim_critic=LocalGlobalCritic(local_channels=16, global_dim=6, embed_dim=32), + dim_loss=LocalDIMLoss(), + prior_loss=DIMPriorLoss(spt.backbone.MLP(6, [16, 8, 1])), + prior_weight=prior_weight, + ) + module.log = Mock() + return module + + +def _batch(): + g = torch.Generator().manual_seed(0) + return { + "image": torch.randn(4, 3, 16, 16, generator=g), + "label": torch.tensor([0, 1, 2, 3]), + } + + +@pytest.mark.unit +class TestLocalDIMForward: + """Unit tests for the :func:`~stable_pretraining.forward.local_dim` forward function.""" + + def test_training_step_trains_every_network(self): + """The joint loss reaches the encoder, the critic and the discriminator.""" + module = _tiny_dim_module(prior_weight=0.1).train() + + out = module(_batch(), stage="fit") + out["loss"].backward() + + assert out["loss"].ndim == 0 and torch.isfinite(out["loss"]) + assert out["embedding"].shape == (4, 6) + assert out["layer1"].shape == (4, 16, 4, 4) + assert torch.equal(out["label"], torch.tensor([0, 1, 2, 3])) + for net in (module.backbone, module.dim_critic, module.prior_loss): + assert any( + p.grad is not None and p.grad.abs().sum() > 0 for p in net.parameters() + ) + logged = {call.args[0] for call in module.log.call_args_list} + assert { + "fit/loss", + "fit/local_dim_loss", + "fit/prior_encoder_loss", + "fit/prior_discriminator_loss", + } <= logged + + def test_zero_prior_weight_is_local_only(self): + """With ``prior_weight == 0`` the loss is exactly the local DIM loss.""" + module = _tiny_dim_module(prior_weight=0.0).train() + batch = _batch() + + out = module(batch, stage="fit") + + features = module.backbone(batch["image"]) + scores = module.dim_critic( + features.hidden_states["layer1"], features.last_hidden_state + ) + assert torch.allclose(out["loss"], module.dim_loss(scores), atol=1e-6) + assert all(p.grad is None for p in module.prior_loss.parameters()) + logged = {call.args[0] for call in module.log.call_args_list} + assert "fit/prior_encoder_loss" not in logged + + def test_validation_returns_embedding_only(self): + """In eval mode no loss is computed.""" + module = _tiny_dim_module().eval() + + out = module(_batch(), stage="validate") + + assert "loss" not in out + assert out["embedding"].shape == (4, 6) + assert out["layer1"].shape == (4, 16, 4, 4) + module.log.assert_not_called() From dd49a2daf2330b5187aada8e9d2740bda88a902e Mon Sep 17 00:00:00 2001 From: Yanbo Hua <3473356866@gmail.com> Date: Fri, 23 Oct 2026 14:06:34 -0400 Subject: [PATCH 3/5] [Doc] Use arXiv BibTeX key for the DIM citation --- docs/source/references.bib | 4 ++-- stable_pretraining/backbone/dim.py | 2 +- stable_pretraining/forward.py | 2 +- stable_pretraining/losses/dim.py | 11 ++++++----- 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/docs/source/references.bib b/docs/source/references.bib index a8b8d9c6d..a76952d7e 100644 --- a/docs/source/references.bib +++ b/docs/source/references.bib @@ -8,13 +8,13 @@ @inproceedings{chen2020simple } @misc{hjelm2019learningdeeprepresentationsmutual, - title={Learning deep representations by mutual information estimation and maximization}, + title={Learning deep representations by mutual information estimation and maximization}, author={R Devon Hjelm and Alex Fedorov and Samuel Lavoie-Marchildon and Karan Grewal and Phil Bachman and Adam Trischler and Yoshua Bengio}, year={2019}, eprint={1808.06670}, archivePrefix={arXiv}, primaryClass={stat.ML}, - url={https://arxiv.org/abs/1808.06670}, + url={https://arxiv.org/abs/1808.06670}, } @article{grill2020bootstrap, diff --git a/stable_pretraining/backbone/dim.py b/stable_pretraining/backbone/dim.py index 2d5f16c06..86e0fedfc 100644 --- a/stable_pretraining/backbone/dim.py +++ b/stable_pretraining/backbone/dim.py @@ -1,4 +1,4 @@ -"""Critic networks for Deep InfoMax (DIM) :cite:`hjelm2019learning`.""" +"""Critic networks for Deep InfoMax (DIM) :cite:`hjelm2019learningdeeprepresentationsmutual`.""" import torch import torch.nn as nn diff --git a/stable_pretraining/forward.py b/stable_pretraining/forward.py index e359d100b..ab3eb8d68 100644 --- a/stable_pretraining/forward.py +++ b/stable_pretraining/forward.py @@ -1295,7 +1295,7 @@ def local_dim(self, batch: dict[str, Any], stage: str) -> dict[str, torch.Tensor - 'label': Labels if present (for probes/callbacks) Note: - Introduced in the Deep InfoMax paper :cite:`hjelm2019learning`. Only + Introduced in the Deep InfoMax paper :cite:`hjelm2019learningdeeprepresentationsmutual`. Only the local objective (and optional prior) is implemented; the global DIM objective is not. The discriminator loss of the prior term is added to ``loss`` with weight 1, as in the reference implementation; diff --git a/stable_pretraining/losses/dim.py b/stable_pretraining/losses/dim.py index 41572b319..5400279ac 100644 --- a/stable_pretraining/losses/dim.py +++ b/stable_pretraining/losses/dim.py @@ -1,9 +1,10 @@ """Deep InfoMax (DIM) losses. This module contains the objectives of local Deep InfoMax -:cite:`hjelm2019learning`: a Jensen-Shannon mutual information estimator -between a global feature vector and every location of a local feature map, -and the optional adversarial prior matching term on the global feature. +:cite:`hjelm2019learningdeeprepresentationsmutual`: a Jensen-Shannon mutual +information estimator between a global feature vector and every location of +a local feature map, and the optional adversarial prior matching term on the +global feature. """ import math @@ -14,7 +15,7 @@ class LocalDIMLoss(torch.nn.Module): - """Jensen-Shannon local DIM objective :cite:`hjelm2019learning`. + """Jensen-Shannon local DIM objective :cite:`hjelm2019learningdeeprepresentationsmutual`. Takes a tensor of critic scores ``scores[a, b, i]`` comparing the global feature of image ``a`` with location ``i`` of the local feature map of @@ -62,7 +63,7 @@ def forward(self, scores: torch.Tensor) -> torch.Tensor: class DIMPriorLoss(torch.nn.Module): - """Adversarial prior matching term of DIM :cite:`hjelm2019learning`. + """Adversarial prior matching term of DIM :cite:`hjelm2019learningdeeprepresentationsmutual`. A discriminator learns to tell samples of a uniform prior on ``[0, 1]^D`` from ``sigmoid(embedding)``, while the encoder is trained to fool it From 5ff7a133ef8b206ab7323095789f6ad651c7b94e Mon Sep 17 00:00:00 2001 From: Yanbo Hua <3473356866@gmail.com> Date: Wed, 2 Dec 2026 16:32:42 -0500 Subject: [PATCH 4/5] [Feature] LocalDIM method class and review follow-up tests - Add LocalDIM method class (spt.LocalDIM) wrapping the local_dim forward function; register in methods, top-level exports, METHODS.md, methods.rst, README and RELEASES.rst - Add LocalDIM to test_methods_smoke.py - Test training through spt.Manager and resuming from a checkpoint - Add two-process gloo DDP tests (tests/distributed/test_dim_dist.py) - Check gradients stay finite on extreme inputs for LocalDIMLoss and DIMPriorLoss --- METHODS.md | 2 +- README.md | 3 +- RELEASES.rst | 3 +- docs/source/api/methods.rst | 1 + stable_pretraining/__init__.py | 2 + stable_pretraining/methods/__init__.py | 2 + stable_pretraining/methods/dim.py | 120 +++++++++ .../tests/distributed/_dist_harness.py | 117 +++++++++ .../tests/distributed/test_dim_dist.py | 22 ++ stable_pretraining/tests/unit/test_dim.py | 246 +++++++++++++++++- .../tests/unit/test_methods_smoke.py | 30 +++ 11 files changed, 533 insertions(+), 15 deletions(-) create mode 100644 stable_pretraining/methods/dim.py create mode 100644 stable_pretraining/tests/distributed/test_dim_dist.py diff --git a/METHODS.md b/METHODS.md index 94963897f..45818ba4b 100644 --- a/METHODS.md +++ b/METHODS.md @@ -18,7 +18,7 @@ Methods come in two forms: | Supervised | `supervised` | — | any | — | — | | SimCLR | `simclr` | `SimCLR` | `NTXEntLoss` | — | [Chen et al., 2020](https://arxiv.org/abs/2002.05709) | | BYOL | `byol` | `BYOL` | `BYOLLoss` | `TeacherStudent†` | [Grill et al., 2020](https://arxiv.org/abs/2006.07733) | -| Local DIM (JSD) | `local_dim` | — | `LocalDIMLoss`, `DIMPriorLoss` | — | [Hjelm et al., 2019](https://arxiv.org/abs/1808.06670) | +| Local DIM (JSD) | `local_dim` | `LocalDIM` | `LocalDIMLoss`, `DIMPriorLoss` | — | [Hjelm et al., 2019](https://arxiv.org/abs/1808.06670) | | VICReg | `vicreg` | `VICReg` | `VICRegLoss` | — | [Bardes et al., 2022](https://arxiv.org/abs/2105.04906) | | 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) | diff --git a/README.md b/README.md index d9a1f46da..2477aba64 100644 --- a/README.md +++ b/README.md @@ -780,8 +780,9 @@ spt.set(default_loggers={"registry": False}) | NNCLR | `forward.nnclr` | `NTXEntLoss` | Nearest-neighbor contrastive learning | | DINO | `forward.dino` | `DINOv1Loss` | Self-distillation with multi-crop and centering | | DINOv2 | `forward.dinov2` | `DINOv2Loss`, `iBOTPatchLoss` | DINO + iBOT masked patch prediction | +| Local DIM | `forward.local_dim` | `LocalDIMLoss`, `DIMPriorLoss` | Mutual information between global and local features | -The table above covers forward functions for use with `spt.Module`. For 30 full `LightningModule` implementations (BEiT, CMAE, Data2Vec, iBOT, iGPT, IJEPA, LeJEPA, MAE, MaskFeat, MIMRefiner, MoCov2, MoCov3, MSN, PIRL, SimMIM, SimSiam, TiCO, VICRegL, VISReg, WMSE, and more), see [`METHODS.md`](METHODS.md) and `stable_pretraining/methods/`. +The table above covers forward functions for use with `spt.Module`. For 30 full `LightningModule` implementations (BEiT, CMAE, Data2Vec, iBOT, iGPT, IJEPA, LeJEPA, LocalDIM, MAE, MaskFeat, MIMRefiner, MoCov2, MoCov3, MSN, PIRL, SimMIM, SimSiam, TiCO, VICRegL, VISReg, WMSE, and more), see [`METHODS.md`](METHODS.md) and `stable_pretraining/methods/`. ## Backbones diff --git a/RELEASES.rst b/RELEASES.rst index 916079f51..e4397a823 100644 --- a/RELEASES.rst +++ b/RELEASES.rst @@ -8,7 +8,8 @@ Unreleased estimator: forward function ``stable_pretraining.forward.local_dim``, losses ``LocalDIMLoss`` and ``DIMPriorLoss`` (optional adversarial prior matching), and the encode-and-dot-product critic ``LocalGlobalCritic`` / - ``DIMEmbedding`` in ``stable_pretraining.backbone``. Only the local + ``DIMEmbedding`` in ``stable_pretraining.backbone``, and the pre-wired + method class ``LocalDIM`` (``spt.LocalDIM``). Only the local objective is implemented (no global DIM). Registered in ``METHODS.md``, with a CIFAR10 pretraining and frozen-encoder evaluation script under ``benchmarks/cifar10/local-dim-dcgan.py``. diff --git a/docs/source/api/methods.rst b/docs/source/api/methods.rst index d582fa39a..f12a5acc9 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 + LocalDIM Feature Redundancy Reduction ----------------------------- diff --git a/stable_pretraining/__init__.py b/stable_pretraining/__init__.py index 1438bed7e..729e5e3eb 100644 --- a/stable_pretraining/__init__.py +++ b/stable_pretraining/__init__.py @@ -183,6 +183,7 @@ def emit(self, record): "CrossMAE": ("stable_pretraining.methods.cross_mae", "CrossMAE"), "DINO": ("stable_pretraining.methods.dino", "DINO"), "DINOv2": ("stable_pretraining.methods.dinov2", "DINOv2"), + "LocalDIM": ("stable_pretraining.methods.dim", "LocalDIM"), "MAE": ("stable_pretraining.methods.mae", "MAE"), "NNCLR": ("stable_pretraining.methods.nnclr", "NNCLR"), "SimCLR": ("stable_pretraining.methods.simclr", "SimCLR"), @@ -486,6 +487,7 @@ def __dir__() -> list[str]: "CrossMAE", "DINO", "DINOv2", + "LocalDIM", "MAE", "NNCLR", "SimCLR", diff --git a/stable_pretraining/methods/__init__.py b/stable_pretraining/methods/__init__.py index 7cc3209bb..6ddd5f3f7 100644 --- a/stable_pretraining/methods/__init__.py +++ b/stable_pretraining/methods/__init__.py @@ -4,6 +4,7 @@ from .cmae import CMAE from .cross_mae import CrossMAE from .data2vec import Data2Vec +from .dim import LocalDIM from .dino import DINO from .dinov2 import DINOv2 from .dinov3 import DINOv3 @@ -47,6 +48,7 @@ "IJEPA", "MAE", "LeJEPA", + "LocalDIM", "MaskFeat", "MIMRefiner", "MoCov2", diff --git a/stable_pretraining/methods/dim.py b/stable_pretraining/methods/dim.py new file mode 100644 index 000000000..ed36d2ce6 --- /dev/null +++ b/stable_pretraining/methods/dim.py @@ -0,0 +1,120 @@ +"""Local Deep InfoMax (DIM) with the Jensen-Shannon estimator. + +Self-supervised learning by maximizing the mutual information between the +global feature of an image and every location of an intermediate feature map +of the same image, with an optional adversarial prior on the global feature. + +References: + Hjelm et al. "Learning deep representations by mutual information + estimation and maximization." ICLR 2019. https://arxiv.org/abs/1808.06670 + +Example:: + + import stable_pretraining as spt + + model = spt.LocalDIM( + encoder, local_layer="layer1", local_channels=128, global_dim=64 + ) + spt.Manager(trainer=trainer, module=model, data=data)() +""" + +from typing import Optional, Sequence + +import torch.nn as nn + +from stable_pretraining import Module +from stable_pretraining.backbone import MLP, HiddenStateExtractor, LocalGlobalCritic +from stable_pretraining.forward import local_dim +from stable_pretraining.losses import DIMPriorLoss, LocalDIMLoss + + +class LocalDIM(Module): + """Local Deep InfoMax (JSD) :cite:`hjelm2019learningdeeprepresentationsmutual`. + + Wires an encoder, a :class:`~stable_pretraining.backbone.LocalGlobalCritic`, + :class:`~stable_pretraining.losses.LocalDIMLoss` and (optionally) + :class:`~stable_pretraining.losses.DIMPriorLoss` into a + :class:`~stable_pretraining.Module` whose forward is + :func:`~stable_pretraining.forward.local_dim`. Batches are dicts with an + ``"image"`` key (one un-augmented view per image) and an optional + ``"label"`` key passed through for probes. + + Args: + encoder: Network mapping images to ``[B, global_dim]`` global features. + local_layer: Name of the ``encoder`` sub-module whose ``[B, C, H, W]`` + output is the local feature map. + local_channels: Channels ``C`` of the local feature map. + global_dim: Dimension of the global feature. + embed_dim: Dimension of the critic's shared embedding space. + prior_weight: Weight ``gamma`` of the prior matching term. ``0`` + disables it and no discriminator is built. + prior_hidden_dims: Hidden sizes of the prior discriminator MLP. + gradient_penalty: Weight of the discriminator gradient penalty. + probe_layers: Extra ``encoder`` sub-modules to hook; their outputs are + returned under their names for probes and callbacks. + optim: Optimizer configuration, as for :class:`~stable_pretraining.Module`. + ``None`` uses Adam(lr=1e-4, betas=(0.5, 0.999)) with a constant + learning rate, as in the reference implementation. + hparams: Hyperparameters to log, as for :class:`~stable_pretraining.Module`. + + Note: + Only the local objective is implemented; the global DIM objective is + not. Defaults follow the paper's DIM(L) setting (``gamma = 0.1``, + Table 10 discriminator) and the reference implementation + (https://github.com/rdevon/DIM). Negatives are the other images of the + per-device batch, so under DDP the number of negatives depends on the + per-device batch size, not the global one. + + Example:: + + model = LocalDIM( + encoder, + local_layer="layer1", + local_channels=128, + global_dim=64, + prior_weight=0.1, + ) + out = model({"image": images}, stage="fit") + out["loss"].backward() + """ + + def __init__( + self, + encoder: nn.Module, + local_layer: str, + local_channels: int, + global_dim: int, + embed_dim: int = 2048, + prior_weight: float = 0.1, + prior_hidden_dims: Sequence[int] = (1000, 200), + gradient_penalty: float = 1.0, + probe_layers: Sequence[str] = (), + optim: Optional[dict] = None, + hparams: Optional[dict] = None, + ): + if optim is None: + optim = { + "optimizer": {"type": "Adam", "lr": 1e-4, "betas": (0.5, 0.999)}, + "scheduler": {"type": "ConstantLR", "factor": 1.0}, + "interval": "epoch", + } + # ``Module.__init__`` must run before sub-modules can be assigned, so + # they are built here and handed over as keyword attributes. + components = {} + if prior_weight > 0: + components["prior_loss"] = DIMPriorLoss( + MLP(global_dim, [*prior_hidden_dims, 1]), + gradient_penalty=gradient_penalty, + ) + hooked = list(dict.fromkeys([local_layer, *probe_layers])) + super().__init__( + forward=local_dim, + hparams=hparams, + backbone=HiddenStateExtractor(encoder, hooked), + local_layer=local_layer, + dim_critic=LocalGlobalCritic(local_channels, global_dim, embed_dim), + dim_loss=LocalDIMLoss(), + prior_weight=prior_weight, + optim=optim, + **components, + ) diff --git a/stable_pretraining/tests/distributed/_dist_harness.py b/stable_pretraining/tests/distributed/_dist_harness.py index 2f13291d9..da33a99f1 100644 --- a/stable_pretraining/tests/distributed/_dist_harness.py +++ b/stable_pretraining/tests/distributed/_dist_harness.py @@ -658,3 +658,120 @@ def w_clip_crossgpu_matches_global(rank, world_size): ref = _ref_clip_global(feats_i_global, feats_j_global, 0.07) assert torch.allclose(avg, ref, atol=1e-5), (avg, ref) + + +# --------------------------------------------------------------------------- +# Local DIM workers (negatives come from the per-rank batch only) +# --------------------------------------------------------------------------- + +_DIM_PER_RANK_BATCH = 4 + + +def _tiny_local_dim(prior_weight: float = 0.0): + from collections import OrderedDict + from unittest.mock import Mock + + from stable_pretraining.methods import LocalDIM + + encoder = nn.Sequential( + OrderedDict( + layer0=nn.Sequential( + nn.Conv2d(3, 8, 4, 2, 1, bias=False), nn.BatchNorm2d(8), nn.ReLU() + ), + layer1=nn.Sequential( + nn.Conv2d(8, 16, 4, 2, 1, bias=False), nn.BatchNorm2d(16), nn.ReLU() + ), + flatten=nn.Flatten(), + layer2=nn.Linear(16 * 4 * 4, 6), + ) + ) + model = LocalDIM( + encoder, + local_layer="layer1", + local_channels=16, + global_dim=6, + embed_dim=32, + prior_weight=prior_weight, + prior_hidden_dims=(16, 8), + ).train() + model.log = Mock() + return model + + +def _dim_loss_and_grads(model, images): + model.zero_grad(set_to_none=True) + loss = model({"image": images}, stage="fit")["loss"] + loss.backward() + grads = {n: p.grad.detach().clone() for n, p in model.named_parameters()} + return loss.detach(), grads + + +def w_dim_ddp_uses_local_negatives(rank, world_size): + """Under DDP each rank's loss only uses its own images as negatives. + + Every rank builds the same model and the same global batch, and holds a + disjoint ``_DIM_PER_RANK_BATCH`` slice of it. The DDP loss on a rank must + equal the single-process loss on that rank's slice alone (no cross-device + negatives), and the all-reduced DDP gradients must equal the mean of the + single-process gradients of the slices. As a contrast, the mean per-rank + loss differs from the single-process loss on the whole global batch. + """ + import copy + + from torch.nn.parallel import DistributedDataParallel + + from stable_pretraining.utils import all_reduce + + torch.manual_seed(0) # identical model and GLOBAL batch on every rank + model = _tiny_local_dim() + images = torch.randn(_DIM_PER_RANK_BATCH * world_size, 3, 16, 16) + shards = images.split(_DIM_PER_RANK_BATCH) + + reference = copy.deepcopy(model) + shard_results = [_dim_loss_and_grads(reference, shard) for shard in shards] + global_loss, _ = _dim_loss_and_grads(copy.deepcopy(model), images) + + ddp = DistributedDataParallel(model) + loss = ddp({"image": shards[rank]}, stage="fit")["loss"] + loss.backward() + + expected_loss, _ = shard_results[rank] + assert torch.allclose(loss.detach(), expected_loss, atol=1e-5), ( + loss, + expected_loss, + ) + for name, param in model.named_parameters(): + expected = torch.stack([grads[name] for _, grads in shard_results]).mean(0) + assert torch.allclose(param.grad, expected, atol=1e-5), name + + mean_loss = all_reduce(loss.detach().clone()) / world_size + assert not torch.allclose(mean_loss, global_loss, atol=1e-4), ( + mean_loss, + global_loss, + ) + + +def w_dim_ddp_trains_with_prior(rank, world_size): + """With the prior term, DDP steps keep gradients finite and replicas identical.""" + from torch.nn.parallel import DistributedDataParallel + + torch.manual_seed(0) + model = _tiny_local_dim(prior_weight=0.1) + torch.manual_seed(1 + rank) # different data and prior samples per rank + ddp = DistributedDataParallel(model) + optimizer = torch.optim.Adam(ddp.parameters(), lr=1e-3) + + for _ in range(3): + optimizer.zero_grad(set_to_none=True) + images = torch.randn(_DIM_PER_RANK_BATCH, 3, 16, 16) + loss = ddp({"image": images}, stage="fit")["loss"] + loss.backward() + assert torch.isfinite(loss) + for name, param in model.named_parameters(): + assert param.grad is not None and torch.isfinite(param.grad).all(), name + optimizer.step() + + for name, param in model.named_parameters(): + gathered = [torch.empty_like(param) for _ in range(world_size)] + dist.all_gather(gathered, param.detach()) + assert all(torch.equal(gathered[0], other) for other in gathered[1:]), name diff --git a/stable_pretraining/tests/distributed/test_dim_dist.py b/stable_pretraining/tests/distributed/test_dim_dist.py new file mode 100644 index 000000000..cbd13648f --- /dev/null +++ b/stable_pretraining/tests/distributed/test_dim_dist.py @@ -0,0 +1,22 @@ +"""Two-process (gloo) DDP tests for local Deep InfoMax. + +Local DIM draws its negatives from the other images of the batch and does no +cross-device gathering, so under DDP every rank only contrasts its own slice. +These tests spawn 2 CPU processes and check that behavior and that DDP +training (including the prior term) stays consistent across ranks. +""" + +import pytest + +from stable_pretraining.tests.distributed import _dist_harness as H + + +@pytest.mark.distributed +class TestLocalDIMDDP: + """Local DIM under a real two-process DDP group.""" + + def test_negatives_are_per_rank(self): + H.run_distributed(H.w_dim_ddp_uses_local_negatives, world_size=2) + + def test_trains_with_prior_and_stays_in_sync(self): + H.run_distributed(H.w_dim_ddp_trains_with_prior, world_size=2) diff --git a/stable_pretraining/tests/unit/test_dim.py b/stable_pretraining/tests/unit/test_dim.py index fc8b1820e..36aeb650e 100644 --- a/stable_pretraining/tests/unit/test_dim.py +++ b/stable_pretraining/tests/unit/test_dim.py @@ -4,15 +4,19 @@ from collections import OrderedDict from unittest.mock import Mock +import lightning as pl import pytest import torch import torch.nn as nn import torch.nn.functional as F +from torch.utils.data import DataLoader import stable_pretraining as spt from stable_pretraining.backbone import DIMEmbedding, LocalGlobalCritic from stable_pretraining.forward import local_dim +from stable_pretraining.data import DataModule from stable_pretraining.losses import DIMPriorLoss, LocalDIMLoss +from stable_pretraining.methods import LocalDIM LOG_2 = math.log(2.0) @@ -72,22 +76,45 @@ def test_uninformative_critic_gives_zero(self): loss = LocalDIMLoss()(torch.zeros(3, 3, 4)) assert torch.allclose(loss, torch.tensor(0.0), atol=1e-7) - def test_perfect_critic_reaches_lower_bound(self): - """Confident, correct scores drive the loss to its minimum ``-2 log 2``.""" + @pytest.mark.parametrize("magnitude", [50.0, 1e4]) + def test_perfect_critic_reaches_lower_bound(self, magnitude): + """Confident, correct scores drive the loss to ``-2 log 2`` with finite gradients.""" batch_size = 4 eye = torch.eye(batch_size).unsqueeze(-1).expand(-1, -1, 6) - scores = 50.0 * (2 * eye - 1) + scores = (magnitude * (2 * eye - 1)).requires_grad_(True) loss = LocalDIMLoss()(scores) + loss.backward() assert torch.allclose(loss, torch.tensor(-2 * LOG_2), atol=1e-6) + assert torch.isfinite(scores.grad).all() + + @pytest.mark.parametrize("magnitude", [50.0, 1e4]) + def test_wrong_critic_has_finite_loss_and_gradients(self, magnitude): + """Confident, wrong scores give a large finite loss and non-vanishing gradients.""" + batch_size = 4 + eye = torch.eye(batch_size).unsqueeze(-1).expand(-1, -1, 6) + scores = (magnitude * (1 - 2 * eye)).requires_grad_(True) + + loss = LocalDIMLoss()(scores) + loss.backward() + + assert torch.isfinite(loss) and loss > 0 + assert torch.isfinite(scores.grad).all() + assert scores.grad.abs().min() > 0 - def test_estimate_is_bounded(self): - """``-loss`` never exceeds ``2 log 2`` regardless of the scores.""" + @pytest.mark.parametrize("scale", [0.1, 1.0, 100.0, 1e4]) + def test_estimate_is_bounded(self, scale): + """``-loss`` never exceeds ``2 log 2`` and gradients stay finite at any scale.""" torch.manual_seed(2) - for scale in (0.1, 1.0, 100.0): - loss = LocalDIMLoss()(scale * torch.randn(6, 6, 5)) - assert -loss.item() <= 2 * LOG_2 + 1e-6 + scores = (scale * torch.randn(6, 6, 5)).requires_grad_(True) + + loss = LocalDIMLoss()(scores) + loss.backward() + + assert torch.isfinite(loss) + assert -loss.item() <= 2 * LOG_2 + 1e-6 + assert torch.isfinite(scores.grad).all() def test_gradient_direction(self): """Gradient descent raises positive scores and lowers negative ones.""" @@ -309,10 +336,44 @@ def test_gradient_penalty_matches_reference(self): expected = 2.0 * disc.weight.pow(2).sum() / 8 assert torch.allclose(with_gp - without, expected, atol=1e-6) + @pytest.mark.parametrize("magnitude", [50.0, 1e4]) + def test_saturated_embedding_keeps_finite_gradients(self, magnitude): + """Embeddings that saturate the sigmoid give finite terms and gradients.""" + torch.manual_seed(4) + prior = DIMPriorLoss(spt.backbone.MLP(6, [16, 8, 1])) + embedding = (magnitude * torch.randn(5, 6).sign()).requires_grad_(True) -def _tiny_dim_module(prior_weight: float = 0.1) -> spt.Module: - """Build a small local DIM ``Module`` on 16x16 inputs.""" - encoder = nn.Sequential( + terms = prior(embedding) + (terms["encoder"] + terms["discriminator"]).backward() + + for value in terms.values(): + assert torch.isfinite(value) + assert torch.isfinite(embedding.grad).all() + for p in prior.discriminator.parameters(): + assert p.grad is not None and torch.isfinite(p.grad).all() + + def test_confident_discriminator_keeps_finite_gradients(self): + """Huge discriminator logits give finite losses and gradients.""" + disc = nn.Linear(4, 1) + with torch.no_grad(): + disc.weight.fill_(1e4) + disc.bias.fill_(-2e4) + prior = DIMPriorLoss(disc) + embedding = torch.randn(8, 4, requires_grad=True) + + terms = prior(embedding) + (terms["encoder"] + terms["discriminator"]).backward() + + for value in terms.values(): + assert torch.isfinite(value) + assert torch.isfinite(embedding.grad).all() + assert torch.isfinite(disc.weight.grad).all() + assert torch.isfinite(disc.bias.grad).all() + + +def _tiny_encoder() -> nn.Sequential: + """Small DCGAN-style encoder on 16x16 inputs: ``layer1`` is ``[B, 16, 4, 4]``.""" + return nn.Sequential( OrderedDict( layer0=nn.Sequential( nn.Conv2d(3, 8, 4, 2, 1, bias=False), nn.BatchNorm2d(8), nn.ReLU() @@ -324,9 +385,13 @@ def _tiny_dim_module(prior_weight: float = 0.1) -> spt.Module: layer2=nn.Linear(16 * 4 * 4, 6), ) ) + + +def _tiny_dim_module(prior_weight: float = 0.1) -> spt.Module: + """Build a small local DIM ``Module`` on 16x16 inputs.""" module = spt.Module( forward=local_dim, - backbone=spt.backbone.HiddenStateExtractor(encoder, ["layer1"]), + backbone=spt.backbone.HiddenStateExtractor(_tiny_encoder(), ["layer1"]), local_layer="layer1", dim_critic=LocalGlobalCritic(local_channels=16, global_dim=6, embed_dim=32), dim_loss=LocalDIMLoss(), @@ -398,3 +463,160 @@ def test_validation_returns_embedding_only(self): assert out["embedding"].shape == (4, 6) assert out["layer1"].shape == (4, 16, 4, 4) module.log.assert_not_called() + + +def _tiny_dim(prior_weight: float = 0.1, **kwargs) -> LocalDIM: + """Build a small :class:`LocalDIM` on 16x16 inputs.""" + return LocalDIM( + _tiny_encoder(), + local_layer="layer1", + local_channels=16, + global_dim=6, + embed_dim=32, + prior_weight=prior_weight, + prior_hidden_dims=(16, 8), + **kwargs, + ) + + +@pytest.mark.unit +class TestLocalDIMMethod: + """Unit tests for the :class:`~stable_pretraining.methods.LocalDIM` method class.""" + + def test_exported(self): + """``LocalDIM`` is reachable from the top-level and ``methods`` namespaces.""" + assert spt.LocalDIM is LocalDIM + assert spt.methods.LocalDIM is LocalDIM + + def test_wires_local_dim_forward(self): + """The class builds the components ``local_dim`` expects and uses it as forward.""" + model = _tiny_dim(prior_weight=0.1) + + assert model.forward.__func__.__name__ == local_dim.__name__ + assert isinstance(model.backbone, spt.backbone.HiddenStateExtractor) + assert isinstance(model.dim_critic, LocalGlobalCritic) + assert isinstance(model.dim_loss, LocalDIMLoss) + assert isinstance(model.prior_loss, DIMPriorLoss) + assert model.local_layer == "layer1" + assert model.prior_weight == 0.1 + + def test_zero_prior_weight_builds_no_discriminator(self): + """Without the prior term no discriminator parameters are created.""" + model = _tiny_dim(prior_weight=0.0) + assert not hasattr(model, "prior_loss") + + def test_probe_layers_are_returned(self): + """Extra hooked layers appear in the output; the local layer is hooked once.""" + model = _tiny_dim(probe_layers=["layer0", "layer1"]).eval() + + out = model(_batch(), stage="validate") + + assert model.backbone.module_names == ["layer1", "layer0"] + assert out["layer0"].shape == (4, 8, 8, 8) + assert out["layer1"].shape == (4, 16, 4, 4) + + def test_training_step_matches_forward_function(self): + """The class computes the same loss as ``spt.Module(forward=local_dim)``.""" + torch.manual_seed(0) + model = _tiny_dim(prior_weight=0.0).train() + model.log = Mock() + reference = spt.Module( + forward=local_dim, + backbone=model.backbone, + local_layer="layer1", + dim_critic=model.dim_critic, + dim_loss=LocalDIMLoss(), + ) + reference.log = Mock() + + out = model(_batch(), stage="fit") + expected = reference(_batch(), stage="fit") + + assert torch.allclose(out["loss"], expected["loss"], atol=1e-6) + + +class _BatchCounter(pl.Callback): + """Record the global step at every training batch end.""" + + def __init__(self): + self.steps = [] + + def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx): + self.steps.append(trainer.global_step) + assert torch.isfinite(outputs["loss"]) + + +def _image_loader(n: int = 24, batch_size: int = 4) -> DataLoader: + g = torch.Generator().manual_seed(0) + images = torch.randn(n, 3, 16, 16, generator=g) + samples = [{"image": images[i], "label": i % 3} for i in range(n)] + return DataLoader(samples, batch_size=batch_size, drop_last=True) + + +def _manager(model: LocalDIM, max_steps: int, callbacks: list, **kwargs): + trainer = pl.Trainer( + accelerator="cpu", + devices=1, + max_steps=max_steps, + callbacks=callbacks, + logger=False, + enable_progress_bar=False, + enable_model_summary=False, + num_sanity_val_steps=0, + ) + return spt.Manager( + trainer=trainer, + module=model, + data=DataModule(train=_image_loader()), + seed=0, + **kwargs, + ) + + +@pytest.mark.unit +def test_dim_trains_with_manager_and_resumes_from_checkpoint(): + """``spt.Manager`` trains ``LocalDIM`` and a new run resumes from its checkpoint.""" + first_counter = _BatchCounter() + first = _tiny_dim(prior_weight=0.1) + initial = {k: v.clone() for k, v in first.state_dict().items()} + manager = _manager(first, max_steps=3, callbacks=[first_counter]) + manager() + + assert first_counter.steps == [1, 2, 3] + assert any( + not torch.equal(initial[name], value) + for name, value in first.state_dict().items() + if name.startswith("backbone.") + ) + checkpoint = manager._run_dir / "checkpoints" / "last.ckpt" + saved = torch.load(checkpoint, weights_only=False) + assert saved["global_step"] == 3 + assert saved["optimizer_states"][0]["state"] + for name, value in first.state_dict().items(): + torch.testing.assert_close(saved["state_dict"][name], value) + + second_counter = _BatchCounter() + resumed = _tiny_dim(prior_weight=0.1) + restored = {} + + class _CaptureStart(pl.Callback): + def on_train_start(self, trainer, pl_module): + restored.update( + {k: v.detach().clone() for k, v in pl_module.state_dict().items()} + ) + adam_state = next(iter(trainer.optimizers[0].state.values())) + restored["_adam_step"] = adam_state["step"].clone() + + resumed_manager = _manager( + resumed, + max_steps=6, + callbacks=[second_counter, _CaptureStart()], + ckpt_path=str(checkpoint.resolve()), + weights_only=False, + ) + resumed_manager() + + for name, value in saved["state_dict"].items(): + torch.testing.assert_close(restored[name], value) + assert restored["_adam_step"].item() == 3 + assert second_counter.steps == [4, 5, 6] diff --git a/stable_pretraining/tests/unit/test_methods_smoke.py b/stable_pretraining/tests/unit/test_methods_smoke.py index 146441878..45c1852ab 100644 --- a/stable_pretraining/tests/unit/test_methods_smoke.py +++ b/stable_pretraining/tests/unit/test_methods_smoke.py @@ -257,6 +257,36 @@ def test_visreg_forward_backward(): _assert_loss_and_backward(model, output) +def test_local_dim_forward_backward(): + """LocalDIM runs the ``local_dim`` forward function: batch dict in, dict out.""" + from collections import OrderedDict + from types import SimpleNamespace + + encoder = torch.nn.Sequential( + OrderedDict( + layer0=torch.nn.Conv2d(C, 8, 4, 2, 1), + layer1=torch.nn.Sequential( + torch.nn.Conv2d(8, 16, 4, 2, 1), torch.nn.ReLU() + ), + flatten=torch.nn.Flatten(), + layer2=torch.nn.Linear(16 * 8 * 8, 8), + ) + ) + model = M.LocalDIM( + encoder, + local_layer="layer1", + local_channels=16, + global_dim=8, + embed_dim=32, + prior_hidden_dims=(16, 8), + ) + model.train() + g = torch.Generator().manual_seed(0) + images = torch.randn(B, C, 32, 32, generator=g) + output = model({"image": images}, stage="fit") + _assert_loss_and_backward(model, SimpleNamespace(loss=output["loss"])) + + def test_mim_refiner_forward_backward(): """MIM-Refiner takes a pre-built encoder; just pass a fresh timm ViT.""" import timm From 98b9ed8456caeb3e56ef370ee0f2555979e54131 Mon Sep 17 00:00:00 2001 From: Yanbo Hua <3473356866@gmail.com> Date: Wed, 2 Dec 2026 17:20:37 -0500 Subject: [PATCH 5/5] [Feature] Expose LocalDIM in __init__.pyi and use it in the CIFAR10 benchmark - List LocalDIM in stable_pretraining/__init__.pyi - Benchmark builds spt.LocalDIM - Document in local_dim that negatives are per GPU under DDP - Add the Local DIM benchmark to benchmarks/README.md --- benchmarks/README.md | 16 ++++++++++++++++ benchmarks/cifar10/local-dim-dcgan.py | 18 +++++++----------- stable_pretraining/__init__.pyi | 1 + stable_pretraining/forward.py | 4 +++- 4 files changed, 27 insertions(+), 12 deletions(-) diff --git a/benchmarks/README.md b/benchmarks/README.md index 1064c847c..c0fa9f582 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -47,6 +47,22 @@ python benchmarks/cifar10/barlow-resnet18.py python benchmarks/cifar10/nnclr-resnet18.py ``` +### Local DIM CIFAR-10 benchmark + +[`cifar10/local-dim-dcgan.py`](cifar10/local-dim-dcgan.py) pretrains the +DCGAN-style encoder of Hjelm et al. (ICLR 2019) with `spt.LocalDIM`, then +evaluates the frozen `conv`, `fc` and `Y` features with the paper's Table 1 +protocol. The reported runs use batch size **64** on **1 GPU** (global batch +64) for **1000 epochs**, with Adam(lr=1e-4, betas=(0.5, 0.999)). + +```bash +# DIM(L), prior weight 0.1 +python benchmarks/cifar10/local-dim-dcgan.py --out-dir runs/local-dim/gamma0.1 + +# Local objective only +python benchmarks/cifar10/local-dim-dcgan.py --prior-weight 0 --out-dir runs/local-dim/gamma0 +``` + ## Notes - The data directory will be created automatically if it doesn't exist diff --git a/benchmarks/cifar10/local-dim-dcgan.py b/benchmarks/cifar10/local-dim-dcgan.py index ecf2cca32..6c94ca176 100644 --- a/benchmarks/cifar10/local-dim-dcgan.py +++ b/benchmarks/cifar10/local-dim-dcgan.py @@ -30,7 +30,6 @@ from torch import nn import stable_pretraining as spt -from stable_pretraining import forward from stable_pretraining.data import transforms sys.path.append(str(Path(__file__).parent.parent)) @@ -113,18 +112,15 @@ def pretrain(args) -> nn.Module: ) encoder = build_encoder() - module = spt.Module( - forward=forward.local_dim, - backbone=spt.backbone.HiddenStateExtractor( - encoder, [LOCAL_LAYER, *EVAL_LAYERS.values()] - ), + module = spt.LocalDIM( + encoder, local_layer=LOCAL_LAYER, - dim_critic=spt.backbone.LocalGlobalCritic( - local_channels=128, global_dim=64, embed_dim=2048 - ), - dim_loss=spt.losses.LocalDIMLoss(), - prior_loss=spt.losses.DIMPriorLoss(spt.backbone.MLP(64, [1000, 200, 1])), + local_channels=128, + global_dim=64, + embed_dim=2048, prior_weight=args.prior_weight, + prior_hidden_dims=(1000, 200), + probe_layers=list(EVAL_LAYERS.values()), optim={ "optimizer": {"type": "Adam", **ADAM}, "scheduler": {"type": "ConstantLR", "factor": 1.0}, diff --git a/stable_pretraining/__init__.pyi b/stable_pretraining/__init__.pyi index 3fce470c4..01d1f4209 100644 --- a/stable_pretraining/__init__.pyi +++ b/stable_pretraining/__init__.pyi @@ -43,6 +43,7 @@ from .registry import open_registry as open_registry # Method classes (most-used; full catalog: stable_pretraining.methods) from .methods.barlow_twins import BarlowTwins as BarlowTwins from .methods.byol import BYOL as BYOL +from .methods.dim import LocalDIM as LocalDIM from .methods.dino import DINO as DINO from .methods.dinov2 import DINOv2 as DINOv2 from .methods.mae import MAE as MAE diff --git a/stable_pretraining/forward.py b/stable_pretraining/forward.py index ab3eb8d68..15090dd6b 100644 --- a/stable_pretraining/forward.py +++ b/stable_pretraining/forward.py @@ -1299,7 +1299,9 @@ def local_dim(self, batch: dict[str, Any], stage: str) -> dict[str, torch.Tensor the local objective (and optional prior) is implemented; the global DIM objective is not. The discriminator loss of the prior term is added to ``loss`` with weight 1, as in the reference implementation; - it never reaches the encoder. + it never reaches the encoder. Negatives are the other images of each + GPU's local batch: under DDP they are not gathered across GPUs, so the + number of negatives depends on the per-GPU batch size. Example: ::