-
Notifications
You must be signed in to change notification settings - Fork 41
/
sim_clr.py
373 lines (334 loc) · 14.8 KB
/
sim_clr.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import logging
from itertools import chain
from typing import Any, List, Tuple
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchmetrics
from torch.utils.data import DataLoader
log = logging.getLogger('torcheeg')
class SimCLRTrainer(pl.LightningModule):
r'''
This class supports the implementation of A Simple Framework for Contrastive Learning of Visual Representations (SimCLR) for self-supervised pre-training.
- Paper: Chen T, Kornblith S, Norouzi M, et al. A simple framework for contrastive learning of visual representations[C]//International conference on machine learning. PMLR, 2020: 1597-1607.
- URL: http://proceedings.mlr.press/v119/chen20j.html
- Related Project: https://github.com/sthalles/SimCLR
.. code-block:: python
from torcheeg.models import CCNN
from torcheeg.trainers import BYOLTrainer
class Extractor(CCNN):
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.conv4(x)
x = x.flatten(start_dim=1)
return x
extractor = Extractor(in_channels=5, num_classes=3)
trainer = SimCLRTrainer(extractor,
devices=1,
accelerator='gpu')
NOTE: The first element of each batch in :obj:`train_loader` and :obj:`val_loader` should be a two-tuple, representing two random transformations (views) of data. You can use :obj:`Contrastive` to achieve this functionality.
.. code-block:: python
from torcheeg.datasets import DEAPDataset
from torcheeg import transforms
from torcheeg.datasets.constants import DEAP_CHANNEL_LOCATION_DICT
contras_dataset = DEAPDataset(
io_path=f'./io/deap',
root_path='./data_preprocessed_python',
offline_transform=transforms.Compose([
transforms.BandDifferentialEntropy(sampling_rate=128,
apply_to_baseline=True),
transforms.BaselineRemoval(),
transforms.ToGrid(DEAP_CHANNEL_LOCATION_DICT)
]),
online_transform=transforms.Compose([
transforms.ToTensor(),
transforms.Contrastive(transforms.Compose( # see here
[transforms.RandomMask(p=0.5),
transforms.RandomNoise(p=0.5)]),
num_views=2)
]),
chunk_size=128,
baseline_chunk_size=128,
num_baseline=3)
trainer.fit(train_loader, val_loader)
Args:
extractor (nn.Module): The feature extraction model learns the feature representation of the EEG signal by forcing the correlation matrixes of source and target data to be close.
extract_channels (int): The feature dimensions of the output of the feature extraction model.
proj_channels (int): The feature dimensions of the output of the projection head. (default: :obj:`256`)
proj_hid_channels (int): The feature dimensions of the hidden layer of the projection head. (default: :obj:`512`)
lr (float): The learning rate. (default: :obj:`0.0001`)
weight_decay (float): The weight decay. (default: :obj:`0.0`)
temperature (float): The temperature. (default: :obj:`0.1`)
devices (int): The number of GPUs to use. (default: :obj:`1`)
accelerator (str): The accelerator to use. Available options are: 'cpu', 'gpu'. (default: :obj:`"cpu"`)
metrics (List[str]): The metrics to use. Available options are: 'acc_top1', 'acc_top5', 'acc_mean_pos'. (default: :obj:`["acc_top1"]`)
.. automethod:: fit
'''
def __init__(self,
extractor: nn.Module,
extract_channels: int,
proj_channels: int = 256,
proj_hid_channels: int = 512,
lr: float = 1e-4,
weight_decay: float = 0.0,
temperature: float = 0.1,
devices: int = 1,
accelerator: str = "cpu",
metrics: List[str] = ["acc_top1"]):
super().__init__()
self.extractor = extractor
self.projector = self.MLP(extract_channels, proj_hid_channels,
proj_channels)
self.lr = lr
self.weight_decay = weight_decay
self.temperature = temperature
self.devices = devices
self.accelerator = accelerator
self.metrics = metrics
self.init_metrics(metrics)
def MLP(self, in_channels: int, hid_channels: int, out_channels: int):
return nn.Sequential(
nn.Linear(in_channels, hid_channels),
nn.BatchNorm1d(hid_channels),
nn.ReLU(inplace=True),
nn.Linear(hid_channels, out_channels),
)
def init_metrics(self, metrics) -> None:
self.train_loss = torchmetrics.MeanMetric()
self.val_loss = torchmetrics.MeanMetric()
if "acc_top1" in metrics:
self.train_acc_top1 = torchmetrics.MeanMetric()
self.val_acc_top1 = torchmetrics.MeanMetric()
if "acc_top5" in metrics:
self.train_acc_top5 = torchmetrics.MeanMetric()
self.val_acc_top5 = torchmetrics.MeanMetric()
if "acc_mean_pos" in metrics:
self.train_acc_mean_pos = torchmetrics.MeanMetric()
self.val_acc_mean_pos = torchmetrics.MeanMetric()
def fit(self,
train_loader: DataLoader,
val_loader: DataLoader,
max_epochs: int = 300,
*args,
**kwargs) -> Any:
r'''
NOTE: The first element of each batch in :obj:`train_loader` and :obj:`val_loader` should be a two-tuple, representing two random transformations (views) of data. You can use :obj:`Contrastive` to achieve this functionality.
Args:
train_loader (DataLoader): Iterable DataLoader for traversing the training data batch (:obj:`torch.utils.data.dataloader.DataLoader`, :obj:`torch_geometric.loader.DataLoader`, etc).
val_loader (DataLoader): Iterable DataLoader for traversing the validation data batch (:obj:`torch.utils.data.dataloader.DataLoader`, :obj:`torch_geometric.loader.DataLoader`, etc).
max_epochs (int): Maximum number of epochs to train the model. (default: :obj:`300`)
'''
trainer = pl.Trainer(devices=self.devices,
accelerator=self.accelerator,
max_epochs=max_epochs,
*args,
**kwargs)
return trainer.fit(self, train_loader, val_loader)
def training_step(self, batch: Tuple[torch.Tensor],
batch_idx: int) -> torch.Tensor:
xs, _ = batch
xs = torch.cat(xs, dim=0)
feats = self.extractor(xs)
feats = self.projector(feats)
cos_sim = F.cosine_similarity(feats[:, None, :],
feats[None, :, :],
dim=-1)
# Mask out cosine similarity to itself
self_mask = torch.eye(cos_sim.shape[0],
dtype=torch.bool,
device=cos_sim.device)
cos_sim.masked_fill_(self_mask, -9e15)
# Find positive example -> batch_size//2 away from the original example
pos_mask = self_mask.roll(shifts=cos_sim.shape[0] // 2, dims=0)
# InfoNCE loss
cos_sim = cos_sim / self.temperature
nll = -cos_sim[pos_mask] + torch.logsumexp(cos_sim, dim=-1)
nll = nll.mean()
# Get ranking position of positive example
comb_sim = torch.cat(
[cos_sim[pos_mask][:, None],
cos_sim.masked_fill(pos_mask, -9e15)
], # First position positive example
dim=-1,
)
sim_argsort = comb_sim.argsort(dim=-1, descending=True).argmin(dim=-1)
self.log("train_loss",
self.train_loss(nll),
prog_bar=True,
on_epoch=False,
logger=False,
on_step=True)
if "acc_top1" in self.metrics:
# Logging ranking metrics
self.log("train_acc_top1",
self.train_acc_top1((sim_argsort == 0).float()),
prog_bar=True,
on_epoch=False,
logger=False,
on_step=True)
if "acc_top5" in self.metrics:
self.log("train_acc_top5",
self.train_acc_top5((sim_argsort < 5).float()),
prog_bar=True,
on_epoch=False,
logger=False,
on_step=True)
if "acc_mean_pos" in self.metrics:
self.log("train_acc_mean_pos",
self.train_acc_mean_pos(1 + sim_argsort.float()),
prog_bar=True,
on_epoch=False,
logger=False,
on_step=True)
return nll
def on_train_epoch_end(self) -> None:
self.log("train_loss",
self.train_loss.compute(),
prog_bar=False,
on_epoch=True,
on_step=False,
logger=True)
if "acc_top1" in self.metrics:
self.log("train_acc_top1",
self.train_acc_top1.compute(),
prog_bar=False,
on_epoch=True,
on_step=False,
logger=True)
if "acc_top5" in self.metrics:
self.log("train_acc_top5",
self.train_acc_top5.compute(),
prog_bar=False,
on_epoch=True,
on_step=False,
logger=True)
if "acc_mean_pos" in self.metrics:
self.log("train_acc_mean_pos",
self.train_acc_mean_pos.compute(),
prog_bar=False,
on_epoch=True,
on_step=False,
logger=True)
# print the metrics
str = "\n[Train] "
for key, value in self.trainer.logged_metrics.items():
if key.startswith("train_"):
str += f"{key}: {value:.3f} "
log.info(str + '\n')
# reset the metrics
self.train_loss.reset()
if "acc_top1" in self.metrics:
self.train_acc_top1.reset()
if "acc_top5" in self.metrics:
self.train_acc_top5.reset()
if "acc_mean_pos" in self.metrics:
self.train_acc_mean_pos.reset()
def validation_step(self, batch: Tuple[torch.Tensor],
batch_idx: int) -> torch.Tensor:
xs, _ = batch
xs = torch.cat(xs, dim=0)
feats = self.extractor(xs)
feats = self.projector(feats)
cos_sim = F.cosine_similarity(feats[:, None, :],
feats[None, :, :],
dim=-1)
# Mask out cosine similarity to itself
self_mask = torch.eye(cos_sim.shape[0],
dtype=torch.bool,
device=cos_sim.device)
cos_sim.masked_fill_(self_mask, -9e15)
# Find positive example -> batch_size//2 away from the original example
pos_mask = self_mask.roll(shifts=cos_sim.shape[0] // 2, dims=0)
# InfoNCE loss
cos_sim = cos_sim / self.temperature
nll = -cos_sim[pos_mask] + torch.logsumexp(cos_sim, dim=-1)
nll = nll.mean()
# Get ranking position of positive example
comb_sim = torch.cat(
[cos_sim[pos_mask][:, None],
cos_sim.masked_fill(pos_mask, -9e15)
], # First position positive example
dim=-1,
)
sim_argsort = comb_sim.argsort(dim=-1, descending=True).argmin(dim=-1)
self.log("val_loss",
self.val_loss(nll),
prog_bar=True,
on_epoch=False,
logger=False,
on_step=True)
if "acc_top1" in self.metrics:
# Logging ranking metrics
self.log("val_acc_top1",
self.val_acc_top1((sim_argsort == 0).float()),
prog_bar=True,
on_epoch=False,
logger=False,
on_step=True)
if "acc_top5" in self.metrics:
self.log("val_acc_top5",
self.val_acc_top5((sim_argsort < 5).float()),
prog_bar=True,
on_epoch=False,
logger=False,
on_step=True)
if "acc_mean_pos" in self.metrics:
self.log("val_acc_mean_pos",
self.val_acc_mean_pos(1 + sim_argsort.float()),
prog_bar=True,
on_epoch=False,
logger=False,
on_step=True)
return nll
def on_validation_epoch_end(self) -> None:
self.log("val_loss",
self.val_loss.compute(),
prog_bar=False,
on_epoch=True,
on_step=False,
logger=True)
if "acc_top1" in self.metrics:
self.log("val_acc_top1",
self.val_acc_top1.compute(),
prog_bar=False,
on_epoch=True,
on_step=False,
logger=True)
if "acc_top5" in self.metrics:
self.log("val_acc_top5",
self.val_acc_top5.compute(),
prog_bar=False,
on_epoch=True,
on_step=False,
logger=True)
if "acc_mean_pos" in self.metrics:
self.log("val_acc_mean_pos",
self.val_acc_mean_pos.compute(),
prog_bar=False,
on_epoch=True,
on_step=False,
logger=True)
# print the metrics
str = "\n[VAL] "
for key, value in self.trainer.logged_metrics.items():
if key.startswith("val_"):
str += f"{key}: {value:.3f} "
log.info(str + '\n')
# reset the metrics
self.val_loss.reset()
if "acc_top1" in self.metrics:
self.val_acc_top1.reset()
if "acc_top5" in self.metrics:
self.val_acc_top5.reset()
if "acc_mean_pos" in self.metrics:
self.val_acc_mean_pos.reset()
def configure_optimizers(self):
optimizer = torch.optim.Adam(
chain(self.extractor.parameters(), self.projector.parameters()),
lr=self.lr,
weight_decay=self.weight_decay,
)
return optimizer