hplisiecki commited on
Commit
ec429d3
·
verified ·
1 Parent(s): a9c9d0b

Upload model_script.py

Browse files
Files changed (1) hide show
  1. model_script.py +58 -0
model_script.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from transformers import AutoModel
4
+
5
+
6
+ class Model(torch.nn.Module):
7
+
8
+ def __init__(self, model_dir, dropout=0.2, hidden_dim=768):
9
+ """
10
+ Initialize the model.
11
+ :param model_name: the name of the model
12
+ :param metric_names: the names of the metrics to use
13
+ :param dropout: the dropout rate
14
+ :param hidden_dim: the hidden dimension of the model
15
+ """
16
+ super(Model, self).__init__()
17
+ self.metric_names = ['Happiness', 'Sadness', 'Anger', 'Disgust', 'Fear', 'Pride', 'Valence', 'Arousal']
18
+ self.bert = AutoModel.from_pretrained(model_dir)
19
+
20
+
21
+ for name in self.metric_names:
22
+ setattr(self, name, nn.Linear(hidden_dim, 1))
23
+ setattr(self, 'l_1_' + name, nn.Linear(hidden_dim, hidden_dim))
24
+
25
+ self.layer_norm = nn.LayerNorm(hidden_dim)
26
+ self.relu = nn.ReLU()
27
+ self.dropout = nn.Dropout(dropout)
28
+ self.sigmoid = nn.Sigmoid()
29
+
30
+ def forward(self, input_id, mask):
31
+ """
32
+ Forward pass of the model.
33
+ :param args: the inputs
34
+ :return: the outputs
35
+ """
36
+ _, x = self.bert(input_ids = input_id, attention_mask=mask, return_dict=False)
37
+ output = self.rate_embedding(x)
38
+ return output
39
+
40
+ def rate_embedding(self, x):
41
+ output_ratings = []
42
+ for name in self.metric_names:
43
+ first_layer = self.relu(self.dropout(self.layer_norm(getattr(self, 'l_1_' + name)(x) + x)))
44
+ second_layer = self.sigmoid(getattr(self, name)(first_layer))
45
+ output_ratings.append(second_layer)
46
+
47
+ return output_ratings
48
+
49
+ def save_pretrained(self, save_directory):
50
+ self.bert.save_pretrained(save_directory)
51
+ torch.save(self.state_dict(), f'{save_directory}/pytorch_model.bin')
52
+
53
+ @classmethod
54
+ def from_pretrained(cls, model_dir, dropout=0.2, hidden_dim=768):
55
+ model = cls(model_dir, dropout, hidden_dim)
56
+ state_dict = torch.load(f'{model_dir}/pytorch_model.bin', map_location=torch.device('cpu'))
57
+ model.load_state_dict(state_dict)
58
+ return model