FredZhang7
commited on
Commit
·
0de77cb
1
Parent(s):
65d0d41
Create modeling_efficientnetv25.py
Browse files- modeling_efficientnetv25.py +38 -0
modeling_efficientnetv25.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PreTrainedModel
|
2 |
+
from .configuration_efficientnetv25 import EfficientNetV25Config
|
3 |
+
import torch, sys, os
|
4 |
+
from huggingface_hub import hf_hub_download
|
5 |
+
|
6 |
+
class EfficientNetV25ForImageClassification(PreTrainedModel):
|
7 |
+
config_class = EfficientNetV25Config
|
8 |
+
|
9 |
+
def __init__(self, config):
|
10 |
+
super().__init__(config)
|
11 |
+
|
12 |
+
repo_id = '/'.join(config.url.split('/')[3:5])
|
13 |
+
file_name = config.url.split('/')[-1]
|
14 |
+
path = f"./models/{file_name}"
|
15 |
+
if not os.path.exists(path):
|
16 |
+
hf_hub_download(repo_id=repo_id, filename=file_name, local_dir="./models")
|
17 |
+
|
18 |
+
self.model = torch.load(path)
|
19 |
+
self.input_size = config.input_size
|
20 |
+
shape = [2] + self.input_size
|
21 |
+
example_inputs = torch.randn(shape)
|
22 |
+
example_inputs = (example_inputs - example_inputs.min()) / (example_inputs.max() - example_inputs.min())
|
23 |
+
|
24 |
+
self.num_classes = config.num_classes
|
25 |
+
if self.num_classes != 1000:
|
26 |
+
self.model.classifier = torch.nn.Linear(in_features=1984, out_features=self.num_classes, bias=True)
|
27 |
+
|
28 |
+
traced_model = torch.jit.trace(self.model, example_inputs)
|
29 |
+
traced_model.save(file_name)
|
30 |
+
|
31 |
+
self.model = torch.jit.load(file_name)
|
32 |
+
|
33 |
+
def forward(self, tensor, labels=None):
|
34 |
+
logits = self.model(tensor)
|
35 |
+
if labels is not None:
|
36 |
+
loss = torch.nn.cross_entropy(logits, labels)
|
37 |
+
return {"loss": loss, "logits": logits}
|
38 |
+
return {"logits": logits}
|