aboutsummaryrefslogtreecommitdiff
path: root/simclr/models.py
blob: 0c3febb142c4aa7bef5cd36ffea54d159b383fda (plain)
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
from pathlib import Path

import sys
from torch import nn
from torchvision.models.resnet import resnet50

path = str(Path(Path(__file__).parent.absolute()).parent.absolute())
sys.path.insert(0, path)

from supervised.models import CIFARViTTiny, CIFARResNet50


class SimCLRBase(nn.Module):
    def __init__(
            self,
            backbone: nn.Module,
            hid_dim: int = 2048,
            out_dim: int = 128,
            pretrain: bool = True
    ):
        super().__init__()
        self.backbone = backbone
        self.pretrain = pretrain

        if pretrain:
            self.projector = nn.Sequential(
                nn.Linear(hid_dim, hid_dim),
                nn.ReLU(inplace=True),
                nn.Linear(hid_dim, out_dim),
            )

    def forward(self, x):
        h = self.backbone(x)
        if self.pretrain:
            z = self.projector(h)
            return z
        else:
            return h


def cifar_simclr_resnet50(hid_dim, *args, **kwargs):
    backbone = CIFARResNet50(num_classes=hid_dim)
    return SimCLRBase(backbone, hid_dim, *args, **kwargs)


def cifar_simclr_vit_tiny(hid_dim, *args, **kwargs):
    backbone = CIFARViTTiny(num_classes=hid_dim)
    return SimCLRBase(backbone, hid_dim, *args, **kwargs)


def imagenet_simclr_resnet50(hid_dim, *args, **kwargs):
    backbone = resnet50(num_classes=hid_dim)
    return SimCLRBase(backbone, hid_dim, *args, **kwargs)