File size: 10,134 Bytes
975624b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import lightning.pytorch as pl
from transformers import (
    AdamW,
    AutoModel,
    AutoConfig,
    get_linear_schedule_with_warmup,
)
from transformers.models.bert.modeling_bert import BertLMPredictionHead
import torch
from torch import nn
from loss import PCCL
import config


class CL_model(pl.LightningModule):
    def __init__(
        self, n_batches=None, n_epochs=None, lr=None, mlm_weight=None, **kwargs
    ):
        super().__init__()

        ## Params
        self.n_batches = n_batches
        self.n_epochs = n_epochs
        self.lr = lr
        self.mlm_weight = mlm_weight
        self.config = AutoConfig.from_pretrained("emilyalsentzer/Bio_ClinicalBERT")

        ## Encoder
        self.bert = AutoModel.from_pretrained(
            "emilyalsentzer/Bio_ClinicalBERT", return_dict=True
        )
        # Unfreeze layers
        self.bert_layer_num = sum(1 for _ in self.bert.named_parameters())
        self.num_unfreeze_layer = self.bert_layer_num
        self.ratio_unfreeze_layer = 0.0
        if kwargs:
            for key, value in kwargs.items():
                if key == "unfreeze" and isinstance(value, float):
                    assert (
                        value >= 0.0 and value <= 1.0
                    ), "ValueError: value must be a ratio between 0.0 and 1.0"
                    self.ratio_unfreeze_layer = value
        if self.ratio_unfreeze_layer > 0.0:
            self.num_unfreeze_layer = int(
                self.bert_layer_num * self.ratio_unfreeze_layer
            )
        for param in list(self.bert.parameters())[: -self.num_unfreeze_layer]:
            param.requires_grad = False

        self.lm_head = BertLMPredictionHead(self.config)
        # self.projector = nn.Linear(self.bert.config.hidden_size, 128)
        print("Model Initialized!")

        ## Losses
        self.cl_loss = PCCL()
        self.mlm_loss = nn.CrossEntropyLoss()

        ## Logs
        self.num_batches = 0
        self.train_loss, self.val_loss = 0, 0
        self.train_loss_cl, self.val_loss_cl = 0, 0
        self.train_loss_mlm, self.val_loss_mlm = 0, 0
        self.training_step_outputs, self.validation_step_outputs = [], []

    def forward(self, input_ids, attention_mask, masked_indices, eval=False):
        embs = self.bert(input_ids=input_ids, attention_mask=attention_mask)
        cls_tokens = embs.pooler_output
        mask_tokens = []
        for idx, value in enumerate(masked_indices):
            masks = embs.last_hidden_state[idx][value]
            avg_mask = torch.mean(masks, dim=0)
            mask_tokens.append(avg_mask)
        mask_tokens = torch.stack(mask_tokens)
        cls_concat_mask = torch.cat((cls_tokens, mask_tokens), dim=1)
        if eval is True:
            return cls_tokens, mask_tokens, cls_concat_mask

        mlm_pred = self.lm_head(embs.last_hidden_state)
        mlm_pred = mlm_pred.view(-1, self.config.vocab_size)
        return cls_concat_mask, mlm_pred

    def training_step(self, batch, batch_idx):
        input_ids = batch["input_ids"]
        attention_mask = batch["attention_mask"]
        mlm_labels = batch["mlm_labels"]
        masked_indices = batch["masked_indices"]
        tags = batch["tags"]
        scores = batch["scores"]
        cls_concat_mask, mlm_pred = self(input_ids, attention_mask, masked_indices)
        loss_cl = self.cl_loss(cls_concat_mask, tags, scores)
        loss_mlm = self.mlm_loss(mlm_pred, mlm_labels.reshape(-1))
        loss = (1 - self.mlm_weight) * loss_cl + self.mlm_weight * loss_mlm
        logs = {"loss": loss, "loss_cl": loss_cl, "loss_mlm": loss_mlm}
        self.training_step_outputs.append(logs)
        self.log("train_loss", loss, prog_bar=True, logger=True, sync_dist=True)

        self.num_batches += 1
        self.train_loss_cl += loss_cl
        self.train_loss_mlm += loss_mlm
        self.train_loss += loss

        if self.num_batches % config.log_every_n_steps == 0:
            avg_loss_cl = self.train_loss_cl / self.num_batches
            avg_loss_mlm = self.train_loss_mlm / self.num_batches
            avg_loss = self.train_loss / self.num_batches
            self.log(
                "train_avg_cl_loss",
                avg_loss_cl,
                prog_bar=True,
                logger=True,
                sync_dist=True,
            )
            self.log(
                "train_avg_mlm_loss",
                avg_loss_mlm,
                prog_bar=True,
                logger=True,
                sync_dist=True,
            )
            self.log(
                "train_avg_loss", avg_loss, prog_bar=True, logger=True, sync_dist=True
            )
            self.train_loss_cl = 0
            self.train_loss_mlm = 0
            self.train_loss = 0
            self.num_batches = 0

        return loss

    def on_train_epoch_end(self):
        e_t_avg_loss = (
            torch.stack([x["loss"] for x in self.training_step_outputs])
            .mean()
            .detach()
            .cpu()
            .numpy()
        )
        self.log(
            "avg_loss_train_epoch",
            e_t_avg_loss.item(),
            on_step=False,
            on_epoch=True,
            sync_dist=True,
        )
        e_t_avg_loss_cl = (
            torch.stack([x["loss_cl"] for x in self.training_step_outputs])
            .mean()
            .detach()
            .cpu()
            .numpy()
        )
        self.log(
            "avg_loss_cl_train_epoch",
            e_t_avg_loss_cl.item(),
            on_step=False,
            on_epoch=True,
            sync_dist=True,
        )
        e_t_avg_loss_mlm = (
            torch.stack([x["loss_mlm"] for x in self.training_step_outputs])
            .mean()
            .detach()
            .cpu()
            .numpy()
        )
        self.log(
            "avg_loss_mlm_train_epoch",
            e_t_avg_loss_mlm.item(),
            on_step=False,
            on_epoch=True,
            sync_dist=True,
        )
        print(
            "train_epoch:",
            self.current_epoch,
            "avg_loss:",
            e_t_avg_loss,
            "avg_cl_loss:",
            e_t_avg_loss_cl,
            "avg_mlm_loss:",
            e_t_avg_loss_mlm,
        )
        self.training_step_outputs.clear()

    def validation_step(self, batch, batch_idx):
        input_ids = batch["input_ids"]
        attention_mask = batch["attention_mask"]
        mlm_labels = batch["mlm_labels"]
        masked_indices = batch["masked_indices"]
        tags = batch["tags"]
        scores = batch["scores"]
        cls_concat_mask, mlm_pred = self(input_ids, attention_mask, masked_indices)
        loss_cl = self.cl_loss(cls_concat_mask, tags, scores)
        loss_mlm = self.mlm_loss(mlm_pred, mlm_labels.reshape(-1))
        loss = (1 - self.mlm_weight) * loss_cl + self.mlm_weight * loss_mlm
        logs = {"loss": loss, "loss_cl": loss_cl, "loss_mlm": loss_mlm}
        self.validation_step_outputs.append(logs)
        self.log("val_loss", loss, prog_bar=True, logger=True, sync_dist=True)

        self.num_batches += 1
        self.val_loss_cl += loss_cl
        self.val_loss_mlm += loss_mlm
        self.val_loss += loss

        if self.num_batches % config.log_every_n_steps == 0:
            avg_loss_cl = self.val_loss_cl / self.num_batches
            avg_loss_mlm = self.val_loss_mlm / self.num_batches
            avg_loss = self.val_loss / self.num_batches
            self.log(
                "val_avg_cl_loss",
                avg_loss_cl,
                prog_bar=True,
                logger=True,
                sync_dist=True,
            )
            self.log(
                "val_avg_mlm_loss",
                avg_loss_mlm,
                prog_bar=True,
                logger=True,
                sync_dist=True,
            )
            self.log(
                "val_avg_loss",
                avg_loss,
                prog_bar=True,
                logger=True,
                sync_dist=True,
            )
            self.val_loss_cl = 0
            self.val_loss_mlm = 0
            self.val_loss = 0
            self.num_batches = 0

        return loss

    def on_validation_epoch_end(self):
        e_v_avg_loss = (
            torch.stack([x["loss"] for x in self.validation_step_outputs])
            .mean()
            .detach()
            .cpu()
            .numpy()
        )
        self.log(
            "avg_loss_val_epoch",
            e_v_avg_loss.item(),
            on_step=False,
            on_epoch=True,
            sync_dist=True,
        )
        e_v_avg_loss_cl = (
            torch.stack([x["loss_cl"] for x in self.validation_step_outputs])
            .mean()
            .detach()
            .cpu()
            .numpy()
        )
        self.log(
            "avg_loss_cl_val_epoch",
            e_v_avg_loss_cl.item(),
            on_step=False,
            on_epoch=True,
            sync_dist=True,
        )
        e_v_avg_loss_mlm = (
            torch.stack([x["loss_mlm"] for x in self.validation_step_outputs])
            .mean()
            .detach()
            .cpu()
            .numpy()
        )
        self.log(
            "avg_loss_mlm_val_epoch",
            e_v_avg_loss_mlm.item(),
            on_step=False,
            on_epoch=True,
            sync_dist=True,
        )
        print(
            "val_epoch:",
            self.current_epoch,
            "avg_loss:",
            e_v_avg_loss,
            "avg_cl_loss:",
            e_v_avg_loss_cl,
            "avg_mlm_loss:",
            e_v_avg_loss_mlm,
        )
        self.validation_step_outputs.clear()

    def configure_optimizers(self):
        # Optimizer
        self.trainable_params = [
            param for param in self.parameters() if param.requires_grad
        ]
        optimizer = AdamW(self.trainable_params, lr=self.lr)

        # Scheduler
        warmup_steps = self.n_batches // 3
        total_steps = self.n_batches * self.n_epochs - warmup_steps
        scheduler = get_linear_schedule_with_warmup(
            optimizer, warmup_steps, total_steps
        )
        return [optimizer], [scheduler]