Upload model.py with huggingface_hub
Browse files
model.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import AutoModel
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from tasks import SECONDARY_TASKS
|
| 4 |
+
from huggingface_hub import PyTorchModelHubMixin
|
| 5 |
+
|
| 6 |
+
class BertMultiTask(nn.Module, PyTorchModelHubMixin):
|
| 7 |
+
def __init__(
|
| 8 |
+
self, model_name, extra_layer_sizes=[], dropout_rate=0.1, finetune: bool = False
|
| 9 |
+
):
|
| 10 |
+
super(BertMultiTask, self).__init__()
|
| 11 |
+
|
| 12 |
+
self.model_name = model_name
|
| 13 |
+
self.extra_layer_sizes = extra_layer_sizes
|
| 14 |
+
self.dropout_rate = dropout_rate
|
| 15 |
+
self.finetune = finetune
|
| 16 |
+
|
| 17 |
+
self.bert = AutoModel.from_pretrained(model_name)
|
| 18 |
+
self.layers = nn.ModuleList()
|
| 19 |
+
if not finetune:
|
| 20 |
+
self.name = f"{model_name.split('/')[-1]}_all_tasks_{'_'.join(map(str, extra_layer_sizes))}"
|
| 21 |
+
for param in self.bert.parameters():
|
| 22 |
+
param.requires_grad = False
|
| 23 |
+
else:
|
| 24 |
+
self.name = f"{model_name.split('/')[-1]}_finetune_all_tasks_{'_'.join(map(str, extra_layer_sizes))}"
|
| 25 |
+
for param in self.bert.parameters():
|
| 26 |
+
param.requires_grad = True
|
| 27 |
+
|
| 28 |
+
prev_size = self.bert.config.hidden_size
|
| 29 |
+
for size in extra_layer_sizes:
|
| 30 |
+
self.layers.append(nn.Linear(prev_size, size))
|
| 31 |
+
self.layers.append(nn.ReLU())
|
| 32 |
+
self.layers.append(nn.Dropout(dropout_rate))
|
| 33 |
+
prev_size = size
|
| 34 |
+
|
| 35 |
+
self.reg_head = nn.Linear(prev_size, 1) # for education value
|
| 36 |
+
|
| 37 |
+
self.classification_heads = nn.ModuleDict()
|
| 38 |
+
for task_name, id_map in SECONDARY_TASKS.items():
|
| 39 |
+
self.classification_heads[task_name] = nn.Linear(prev_size, len(id_map))
|
| 40 |
+
|
| 41 |
+
def forward(self, input_ids, attention_mask):
|
| 42 |
+
outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask)
|
| 43 |
+
pooled_output = outputs.pooler_output
|
| 44 |
+
|
| 45 |
+
x = pooled_output
|
| 46 |
+
for layer in self.layers:
|
| 47 |
+
x = layer(x)
|
| 48 |
+
|
| 49 |
+
reg_output = self.reg_head(x).squeeze(-1)
|
| 50 |
+
classes_outputs = {}
|
| 51 |
+
for task, head in self.classification_heads.items():
|
| 52 |
+
classes_outputs[task] = head(x)
|
| 53 |
+
|
| 54 |
+
return reg_output, classes_outputs
|
| 55 |
+
|
| 56 |
+
def model_unique_name(self) -> str:
|
| 57 |
+
return self.name
|