File size: 6,545 Bytes
b552d82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import torch
from torch.utils.data import Dataset, DataLoader
import numpy as np
import pytorch_lightning as pl
import torch.nn as nn
from transformers import BertTokenizerFast as BertTokenizer, AdamW, get_linear_schedule_with_warmup, AutoTokenizer, AutoModel
from huggingface_hub import PyTorchModelHubMixin


class EurovocDataset(Dataset):

    def __init__(
            self,
            text: np.array,
            labels: np.array,
            tokenizer: BertTokenizer,
            max_token_len: int = 128
    ):
        self.tokenizer = tokenizer
        self.text = text
        self.labels = labels
        self.max_token_len = max_token_len

    def __len__(self):
        return len(self.labels)

    def __getitem__(self, index: int):
        text = self.text[index][0]
        labels = self.labels[index]

        encoding = self.tokenizer.encode_plus(
            text,
            add_special_tokens=True,
            max_length=self.max_token_len,
            return_token_type_ids=False,
            padding="max_length",
            truncation=True,
            return_attention_mask=True,
            return_tensors='pt',
        )

        return dict(
            text=text,
            input_ids=encoding["input_ids"].flatten(),
            attention_mask=encoding["attention_mask"].flatten(),
            labels=torch.FloatTensor(labels)
        )


class EuroVocLongTextDataset(Dataset):

    def __splitter__(text, max_lenght):
        l = text.split()
        for i in range(0, len(l), max_lenght):
            yield l[i:i + max_lenght]

    def __init__(
            self,
            text: np.array,
            labels: np.array,
            tokenizer: BertTokenizer,
            max_token_len: int = 128
    ):
        self.tokenizer = tokenizer
        self.text = text
        self.labels = labels
        self.max_token_len = max_token_len

        self.chunks_and_labels = [(c, l) for t, l in zip(self.text, self.labels) for c in self.__splitter__(t)]

        self.encoding = self.tokenizer.batch_encode_plus(
            [c for c, _ in self.chunks_and_labels],
            add_special_tokens=True,
            max_length=self.max_token_len,
            return_token_type_ids=False,
            padding="max_length",
            truncation=True,
            return_attention_mask=True,
            return_tensors='pt',
        )

    def __len__(self):
        return len(self.chunks_and_labels)

    def __getitem__(self, index: int):
        text, labels = self.chunks_and_labels[index]

        return dict(
            text=text,
            input_ids=self.encoding[index]["input_ids"].flatten(),
            attention_mask=self.encoding[index]["attention_mask"].flatten(),
            labels=torch.FloatTensor(labels)
        )


class EurovocDataModule(pl.LightningDataModule):

    def __init__(self, bert_model_name, x_tr, y_tr, x_test, y_test, batch_size=8, max_token_len=512):        
        super().__init__()

        self.batch_size = batch_size
        self.x_tr = x_tr
        self.y_tr = y_tr
        self.x_test = x_test
        self.y_test = y_test
        self.tokenizer = AutoTokenizer.from_pretrained(bert_model_name)
        self.max_token_len = max_token_len

    def setup(self, stage=None):
        self.train_dataset = EurovocDataset(
            self.x_tr,
            self.y_tr,
            self.tokenizer,
            self.max_token_len
        )

        self.test_dataset = EurovocDataset(
            self.x_test,
            self.y_test,
            self.tokenizer,
            self.max_token_len
        )

    def train_dataloader(self):
        return DataLoader(
            self.train_dataset,
            batch_size=self.batch_size,
            shuffle=True,
            num_workers=2
        )

    def val_dataloader(self):
        return DataLoader(
            self.test_dataset,
            batch_size=self.batch_size,
            num_workers=2
        )

    def test_dataloader(self):
        return DataLoader(
            self.test_dataset,
            batch_size=self.batch_size,
            num_workers=2
        )


class EurovocTagger(pl.LightningModule, PyTorchModelHubMixin):

  def __init__(self, bert_model_name, n_classes, lr=2e-5, eps=1e-8):
    super().__init__()
    self.bert = AutoModel.from_pretrained(bert_model_name)
    self.dropout = nn.Dropout(p=0.2)
    self.classifier1 = nn.Linear(self.bert.config.hidden_size, n_classes)
    self.criterion = nn.BCELoss()
    self.lr = lr
    self.eps = eps

  def forward(self, input_ids, attention_mask, labels=None):
    output = self.bert(input_ids, attention_mask=attention_mask)
    output = self.dropout(output.pooler_output)
    output = self.classifier1(output)
    output = torch.sigmoid(output)    
    loss = 0
    if labels is not None:
        loss = self.criterion(output, labels)
    return loss, output

  def training_step(self, batch, batch_idx):
    input_ids = batch["input_ids"]
    attention_mask = batch["attention_mask"]
    labels = batch["labels"]
    loss, outputs = self(input_ids, attention_mask, labels)
    self.log("train_loss", loss, prog_bar=True, logger=True)
    return {"loss": loss, "predictions": outputs, "labels": labels}

  def validation_step(self, batch, batch_idx):
    input_ids = batch["input_ids"]
    attention_mask = batch["attention_mask"]
    labels = batch["labels"]
    loss, outputs = self(input_ids, attention_mask, labels)
    self.log("val_loss", loss, prog_bar=True, logger=True)
    return loss

  def test_step(self, batch, batch_idx):
    input_ids = batch["input_ids"]
    attention_mask = batch["attention_mask"]
    labels = batch["labels"]
    loss, outputs = self(input_ids, attention_mask, labels)
    self.log("test_loss", loss, prog_bar=True, logger=True)
    return loss

  def on_train_epoch_end(self,  *args, **kwargs):
    return
    #labels = []
    #predictions = []
    #for output in args['outputs']:
    #  for out_labels in output["labels"].detach().cpu():
    #    labels.append(out_labels)
    #  for out_predictions in output["predictions"].detach().cpu():
    #    predictions.append(out_predictions)

    #labels = torch.stack(labels).int()
    #predictions = torch.stack(predictions)

    #for i, name in enumerate(mlb.classes_):
    #  class_roc_auc = auroc(predictions[:, i], labels[:, i])
    #  self.logger.experiment.add_scalar(f"{name}_roc_auc/Train", class_roc_auc, self.current_epoch)

        
  def configure_optimizers(self):
        return torch.optim.AdamW(self.parameters(), lr=self.lr, eps=self.eps)