Manifest SHA256 18a213bb6bd05fd43001ed0630c33a2414a977d36b5b0ec00131e7bb295ea015
Source records 89 mismatches 0
{'repository_url': 'https://github.com/emsansone/CPLearn', 'commit': '6e0bd3b9e943809dabb6aaedc490be1814a7de3c', 'status': 'acquired'}
ARCHIVE sources\0256\r01\a.zip c74bc32e0a3335fd10369e4e63545513ce07e20214553b02e91da156453a1067
MEMBER CPLearn-6e0bd3b9e943809dabb6aaedc490be1814a7de3c/README.md SHA256 2c149612c9106bc01ac69aa6e90296d437a76bf784faf03e3ec9a942ac4a0dd1
1: # CPLearn
2: Code accompanying the paper ["Collapse-Proof Non-Contrastive Self-Supervised Learning"](https://arxiv.org/pdf/2410.04959).
3: 
4: ## A Few Notes
5: The code is implemented within the [solo-learn](https://github.com/vturrisi/solo-learn) library. More specifically, these files are of interest:
6: - [scripts/pretrain/cifar/cplearn.yaml](scripts/pretrain/cifar/cplearn.yaml)
7: - [solo/methods/cplearn.py](solo/methods/cplearn.py)
8: 
9: All other config files are shared with [solo-learn](https://github.com/vturrisi/solo-learn).
10: 
11: ## Prerequisites
12: ```bash
13: pip install -r requirements.txt
14: wandb login <API_KEY>
15: ```
16: 
17: ## Reproducing ResNet-18 Experiments
18: ### CPLearn Pretraining and Online Linear Probing Eval
19: ```bash
20: python3 main_pretrain.py \
21:     # path to training script folder
22:     --config-path scripts/pretrain/cifar/cplearn.yaml/ \
23:     # training config name
24:     --config-name cplearn.yaml
25: ```
26: Pre-training on a single A100 GPU takes around 8 hours.
27: 
28: ### CPLearn Clustering Eval
29: ```bash
30: python3 main_clustering.py --dataset cifar10 --train_data_path datasets --pretrained_checkpoint_dir a_checkpoint_dir_containing_a_single_checkpoint
31: ```
32: Results are stored in the selected checkpoint dir
33: 
34: ### CPLearn Dimensional and Intra-cluster Collapse Eval
35: First, extract the embeddings and store them in a newly created folder called *embeddings*
36: ```bash
37: python3 main_embeddings.py --dataset cifar10 --train_data_path datasets --pretrained_checkpoint_dir a_checkpoint_dir_containing_a_single_checkpoint
38: ```
39: 
40: Second, run the collapse analysis
41: ```bash
42: python3 main_collapses.py
43: ```
44: Results are stored in the *embeddings* folder. Below, you can find the produced figures.
45: 
46: | Dimensional Collapse | Intra-Cluster Collapse |
47: |----------------------------|----------------------------|
48: | ![Figure 1a](embeddings/Dimensional_collapse.svg) | ![Figure 1b](embeddings/Intra_collapse.svg) |
49: 
50: ## Citation
51: If you use the code or any result, please use the following reference:
52: ```bibtex
53: @inproceedings{sansone2025collapses,
54:   author    = {Emanuele Sansone and Tim Lebailly and Tinne Tuytelaars},
55:   title     = {{Collapse-Proof Non-Contrastive Self-Supervised Learning}},
56:   booktitle = {International Conference on Machine Learning},
57:   year      = {2025}
58: }
59: ```
MEMBER CPLearn-6e0bd3b9e943809dabb6aaedc490be1814a7de3c/solo/losses/cplearn.py SHA256 45aa1e6db5f92f9b983c2d2634dc825708b92732fc871b4b1e23a109239d81df
1: # Copyright 2025 CPLearn team.
2: 
3: # Permission is hereby granted, free of charge, to any person obtaining a copy of
4: # this software and associated documentation files (the "Software"), to deal in
5: # the Software without restriction, including without limitation the rights to use,
6: # copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
7: # Software, and to permit persons to whom the Software is furnished to do so,
8: # subject to the following conditions:
9: 
10: # The above copyright notice and this permission notice shall be included in all copies
11: # or substantial portions of the Software.
12: 
13: # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
14: # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
15: # PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
16: # FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
17: # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
18: # DEALINGS IN THE SOFTWARE.
19: 
20: import torch
21: 
22: import torch.distributed as dist
23: 
24: 
25: def cplearn_loss_func(
26:     z1: torch.Tensor, z2: torch.Tensor, beta: float = 0.05
27: ) -> torch.Tensor:
28:     """Computes CPLearn' loss given batch of projected features z1 from view 1 and
29:     projected features z2 from view 2.
30: 
31:     Args:
32:         z1 (torch.Tensor): NxD Tensor containing projected features from view 1.
33:         z2 (torch.Tensor): NxD Tensor containing projected features from view 2.
34:         beta (float, optional): beta factor of the loss. Defaults to 0.01.
35: 
36:     Returns:
37:         torch.Tensor: CPLearn' loss.
38:     """
39: 
40:     # ##### Single loss code ######
41:     z1 = z1 - torch.max(z1, dim=1, keepdim=True)[0]
42:     z2 = z2 - torch.max(z2, dim=1, keepdim=True)[0]
43:     _, c = z1.shape
44:     loss1 = ( z2.softmax(1) * torch.log( c * z2.softmax(1).mean(0, keepdim=True)) ).sum(1).mean()
45:     loss2 = - ( z2.softmax(1) * (beta * z1) - z2.softmax(1) * (beta * z1.logsumexp(1, keepdim=True)) ).sum(1).mean()
46: 
47:     loss3 = ( z1.softmax(1) * torch.log( c * z1.softmax(1).mean(0, keepdim=True)) ).sum(1).mean()
48:     loss4 = - ( z1.softmax(1) * (beta * z2) - z1.softmax(1) * (beta * z2.logsumexp(1, keepdim=True)) ).sum(1).mean()
49: 
50:     # loss5 = ((learn_codes - target_codes)**2).mean() # CALL THIS TO AVOID PROBLEM OF UNUSED PARAMETERS
51: 
52:     # loss6 = (back_out**2).mean()
53: 
54:     loss = 0.5 * (loss1 + loss2) + 0.5 * (loss3 + loss4)
55: 
56:     return loss
MEMBER CPLearn-6e0bd3b9e943809dabb6aaedc490be1814a7de3c/solo/methods/cplearn.py SHA256 adeea0a8f718d3a0c0aba13d7bf2df0257dee69436c580e96134e86e5caa6e5b
1: # Copyright 2025 CPLearn team.
2: 
3: # Permission is hereby granted, free of charge, to any person obtaining a copy of
4: # this software and associated documentation files (the "Software"), to deal in
5: # the Software without restriction, including without limitation the rights to use,
6: # copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
7: # Software, and to permit persons to whom the Software is furnished to do so,
8: # subject to the following conditions:
9: 
10: # The above copyright notice and this permission notice shall be included in all copies
11: # or substantial portions of the Software.
12: 
13: # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
14: # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
15: # PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
16: # FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
17: # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
18: # DEALINGS IN THE SOFTWARE.
19: 
20: from typing import Any, List, Sequence
21: 
22: import omegaconf
23: import torch
24: import torch.nn as nn
25: import torch.nn.functional as F
26: from solo.losses.cplearn import cplearn_loss_func
27: from solo.methods.base import BaseMethod
28: from solo.utils.misc import omegaconf_select
29: import numpy as np
30: 
31: 
32: class CPLearn(BaseMethod):
33:     def __init__(self, cfg: omegaconf.DictConfig):
34:         """Implements CPLearn
35: 
36:         Extra cfg settings:
37:             method_kwargs:
38:                 proj_hidden_dim (int): number of neurons of the hidden layers of the projector.
39:                 proj_output_dim (int): number of dimensions of projected features.
40:                 beta (float): beta of the loss.
41:         """
42: 
43:         super().__init__(cfg)
44: 
45:         self.beta: float = cfg.method_kwargs.beta
46:         self.epsilon = 1e-8
47: 
48:         self.proj_hidden_dim: int = cfg.method_kwargs.proj_hidden_dim
49:         self.proj_output_dim: int = cfg.method_kwargs.proj_output_dim
50: 
51:         print('||||||||||||||||||||||||||||||||||||||||||||||||||||')
52:         print(self.beta, self.proj_output_dim)
53:         print('||||||||||||||||||||||||||||||||||||||||||||||||||||')
54: 
55:         # projector
56:         self.projector = nn.Sequential(
57:             nn.Linear(self.features_dim, self.proj_hidden_dim),
58:             nn.BatchNorm1d(self.proj_hidden_dim),
59:         )
60:         self.tanh = nn.Tanh()
61:         self.register_buffer('weights', torch.tensor(2. * np.random.randint(2, size=(self.proj_hidden_dim, self.proj_output_dim)) - 1.).to(torch.float))
62: 
63: 
64:     @staticmethod
65:     def add_and_assert_specific_cfg(cfg: omegaconf.DictConfig) -> omegaconf.DictConfig:
66:         """Adds method specific default values/checks for config.
67: 
68:         Args:
69:             cfg (omegaconf.DictConfig): DictConfig object.
70: 
71:         Returns:
72:             omegaconf.DictConfig: same as the argument, used to avoid errors.
73:         """
74: 
75:         cfg = super(CPLearn, CPLearn).add_and_assert_specific_cfg(cfg)
76: 
77:         assert not omegaconf.OmegaConf.is_missing(cfg, "method_kwargs.proj_hidden_dim")
78:         assert not omegaconf.OmegaConf.is_missing(cfg, "method_kwargs.proj_output_dim")
79:         assert not omegaconf.OmegaConf.is_missing(cfg, "method_kwargs.beta")
80: 
81:         return cfg
82: 
83:     @property
84:     def learnable_params(self) -> List[dict]:
85:         """Adds projector parameters to parent's learnable parameters.
86: 
87:         Returns:
88:             List[dict]: list of learnable parameters.
89:         """
90: 
91:         extra_learnable_params = [{"name": "projector", "params": self.projector.parameters()}]
92:         return super().learnable_params + extra_learnable_params
93: 
94:     def forward(self, X):
95:         """Performs the forward pass of the backbone and the projector.
96: 
97:         Args:
98:             X (torch.Tensor): a batch of images in the tensor format.
99: 
100:         Returns:
101:             Dict[str, Any]: a dict containing the outputs of the parent and the projected features.
102:         """
103: 
104:         out = super().forward(X)
105:         z = self.projector(out["feats"])
106:         z = self.tanh(z)
107:         # z = F.normalize(z)
108:         z = z @ self.weights
109:         n, c = z.shape
110:         temp = self.proj_hidden_dim / (np.sqrt(n) * np.log((1. - self.epsilon * (c - 1.)) / self.epsilon))
111:         out.update({"z": z / temp})
112:         return out
113: 
114:     def embeddings(self, X):
115:         """Performs the forward pass of the backbone and the projector.
116: 
117:         Args:
118:             X (torch.Tensor): a batch of images in the tensor format.
119: 
120:         Returns:
121:             Dict[str, Any]: a dict containing the outputs of the parent and the projected features.
122:         """
123:         out = super().forward(X)
124:         z = out["feats"]
125:         for layer in self.projector:
126:             z = layer(z)
127:         z = self.tanh(z)
128:         out.update({"embed": z})
129:         return out
130: 
131:     def training_step(self, batch: Sequence[Any], batch_idx: int) -> torch.Tensor:
132:         """Training step for CPLearn reusing BaseMethod training step.
133: 
134:         Args:
135:             batch (Sequence[Any]): a batch of data in the format of [img_indexes, [X], Y], where
136:                 [X] is a list of size num_crops containing batches of images.
137:             batch_idx (int): index of the batch.
138: 
139:         Returns:
140:             torch.Tensor: total loss composed of CPLearn loss and classification loss.
141:         """
142: 
143:         out = super().training_step(batch, batch_idx)
144:         class_loss = out["loss"]
145:         z1, z2 = out["z"]
146: 
147:         # ------- CPLearn loss -------
148:         cplearn_loss = cplearn_loss_func(z1, z2, beta=self.beta)
149: 
150:         self.log("train_cplearn", cplearn_loss, on_epoch=True, sync_dist=True)
151: 
152:         return cplearn_loss + class_loss
