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
| class HFModel(pl.LightningModule):
def __init__(
self,
tokenizer,
model,
config: Dict,
) -> None:
super().__init__()
self.model = model
self.tokenizer = tokenizer
self.average_training_loss = None
self.average_validation_loss = None
self.config = config
def forward(self, input_ids, attention_mask, decoder_attention_mask, labels=None):
output = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
decoder_attention_mask=decoder_attention_mask,
labels=labels,
)
return output.loss, output.logits
def compute_loss(self, batch, batch_size):
input_ids = batch['source_text_input_ids']
attention_mask = batch['source_text_attention_mask']
labels_attention_mask = batch['labels_attention_mask']
labels = batch['labels']
loss, logits = self(
input_ids=input_ids,
attention_mask=attention_mask,
labels=labels,
decoder_attention_mask=labels_attention_mask
)
return loss
def training_step(self, batch, batch_size):
loss = self.compute_loss(batch, batch_size)
self.log("train_loss", loss, prog_bar=True, logger=True, on_epoch=True, on_step=True, sync_dist=True)
return loss
def validation_step(self, batch, batch_size):
loss = self.compute_loss(batch, batch_size)
self.log("val_loss", loss, prog_bar=True, logger=True, on_epoch=True, on_step=True, sync_dist=True)
return loss
def test_step(self, batch, batch_size):
loss = self.compute_loss(batch, batch_size)
self.log("test_loss", loss, prog_bar=True, logger=True, sync_dist=True)
return loss
def configure_optimizers(self):
optimizer = AdamW(
self.parameters(),
lr=self.config['train']['learning_rate']
) scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer, mode='min', factor=0.5, patience=1, verbose=True
)
return {
"optimizer": optimizer,
"lr_scheduler": {
"scheduler": scheduler,
"monitor": "val_loss"
}
}
|