Nick Sorros
commited on
Commit
·
ba33264
1
Parent(s):
e68d6e7
Upload model.py
Browse files
model.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import AutoModel
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class MultiLabelAttention(torch.nn.Module):
|
| 6 |
+
def __init__(self, D_in, num_labels):
|
| 7 |
+
super().__init__()
|
| 8 |
+
self.A = torch.nn.Parameter(torch.empty(D_in, num_labels))
|
| 9 |
+
torch.nn.init.uniform_(self.A, -0.1, 0.1)
|
| 10 |
+
|
| 11 |
+
def forward(self, x):
|
| 12 |
+
attention_weights = torch.nn.functional.softmax(
|
| 13 |
+
torch.tanh(torch.matmul(x, self.A)), dim=1
|
| 14 |
+
)
|
| 15 |
+
return torch.matmul(torch.transpose(attention_weights, 2, 1), x)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class BertMesh(torch.nn.Module):
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
pretrained_model,
|
| 22 |
+
num_labels,
|
| 23 |
+
hidden_size=512,
|
| 24 |
+
dropout=0,
|
| 25 |
+
multilabel_attention=False,
|
| 26 |
+
):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.pretrained_model = pretrained_model
|
| 29 |
+
self.num_labels = num_labels
|
| 30 |
+
self.hidden_size = hidden_size
|
| 31 |
+
self.dropout = dropout
|
| 32 |
+
self.multilabel_attention = multilabel_attention
|
| 33 |
+
|
| 34 |
+
self.bert = AutoModel.from_pretrained(pretrained_model) # 768
|
| 35 |
+
self.multilabel_attention_layer = MultiLabelAttention(
|
| 36 |
+
768, num_labels
|
| 37 |
+
) # num_labels, 768
|
| 38 |
+
self.linear_1 = torch.nn.Linear(768, hidden_size) # num_labels, 512
|
| 39 |
+
self.linear_2 = torch.nn.Linear(hidden_size, 1) # num_labels, 1
|
| 40 |
+
self.linear_out = torch.nn.Linear(hidden_size, num_labels)
|
| 41 |
+
self.dropout_layer = torch.nn.Dropout(self.dropout)
|
| 42 |
+
|
| 43 |
+
def forward(self, inputs):
|
| 44 |
+
if self.multilabel_attention:
|
| 45 |
+
hidden_states = self.bert(input_ids=inputs)[0]
|
| 46 |
+
attention_outs = self.multilabel_attention_layer(hidden_states)
|
| 47 |
+
outs = torch.nn.functional.relu(self.linear_1(attention_outs))
|
| 48 |
+
outs = self.dropout_layer(outs)
|
| 49 |
+
outs = torch.sigmoid(self.linear_2(outs))
|
| 50 |
+
outs = torch.flatten(outs, start_dim=1)
|
| 51 |
+
else:
|
| 52 |
+
cls = self.bert(input_ids=inputs)[1]
|
| 53 |
+
outs = torch.nn.functional.relu(self.linear_1(cls))
|
| 54 |
+
outs = self.dropout_layer(outs)
|
| 55 |
+
outs = torch.sigmoid(self.linear_out(outs))
|
| 56 |
+
return outs
|