File size: 1,694 Bytes
a1f442d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from transformers import PreTrainedModel
import torch
import torch.nn as nn
from torchvision import transforms
from transformers.models.mvp.modeling_mvp import CrossEntropyLoss

from .configuration_resnet import ResnetFeatureExtractorConfig

class ResnetFeatureExtractor(PreTrainedModel):
    config_class = ResnetFeatureExtractorConfig

    def __init__(self, config):
        super().__init__(config)
        
        if config.name == 'resnet152':
            self.model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet152', pretrained=False)
            self.model.fc = nn.Identity()
            self.model.to(self.device)
            self.preprocess = transforms.Compose([
                transforms.Resize(256),
                transforms.CenterCrop(224),
                transforms.ToTensor(),
                transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
            ])

    def forward(self, images):
        tensor = torch.stack([self.preprocess(image) for image in images]).to(self.device).float()
        return self.model(tensor)

class ResnetModelForImageClassification(PreTrainedModel):
    config_class = ResnetFeatureExtractorConfig

    def __init__(self, config):
        super().__init__(config)
        if config.name == 'resnet152':
          self.model = nn.Sequential(
              nn.Linear(2048, 32),
              nn.ReLU(),
              nn.Linear(32, 2)
          )

    def forward(self, tensor, labels=None):
        logits = self.model(tensor)
        if labels is not None:
            loss = CrossEntropyLoss()(logits, torch.tensor(labels))
            return {"loss": loss, "logits": logits}
        return {"logits": logits}