File size: 809 Bytes
368b21e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

import torch.nn as nn
from transformers import BertModel

class BertMultiOutput(nn.Module):
    def __init__(self, num_labels_per_class):
        super(BertMultiOutput, self).__init__()
        self.bert = BertModel.from_pretrained("bert-base-uncased")
        self.dropout = nn.Dropout(0.3)
        self.classifiers = nn.ModuleDict({
            label: nn.Linear(self.bert.config.hidden_size, num_labels)
            for label, num_labels in num_labels_per_class.items()
        })

    def forward(self, input_ids, attention_mask):
        outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask)
        pooled_output = self.dropout(outputs.pooler_output)
        return {
            label: classifier(pooled_output)
            for label, classifier in self.classifiers.items()
        }