| 12 | from torchmetrics.classification import F1Score |
| 13 | |
| 14 | class DualEncoderModule(pl.LightningModule): |
| 15 | # Instantiate the model |
| 16 | def __init__(self, tokenizer, model, learning_rate=1e-3): |
| 17 | super().__init__() |
| 18 | self.tokenizer = tokenizer |
| 19 | self.model = model |
| 20 | self.learning_rate = learning_rate |
| 21 | |
| 22 | self.train_acc = torchmetrics.Accuracy() |
| 23 | self.val_acc = torchmetrics.Accuracy() |
| 24 | self.test_acc = torchmetrics.Accuracy() |
| 25 | |
| 26 | # Do a forward pass through the model |
| 27 | def forward(self, input_ids, **kwargs): |
| 28 | return self.model(input_ids, **kwargs) |
| 29 | |
| 30 | def configure_optimizers(self): |
| 31 | optimizer = AdamW(self.parameters(), lr = self.learning_rate) |
| 32 | return optimizer |
| 33 | |
| 34 | def training_step(self, batch, batch_idx): |
| 35 | pos_ids, pos_mask, neg_ids, neg_mask = batch |
| 36 | |
| 37 | neg_ids = neg_ids.view(-1, neg_ids.shape[-1]) |
| 38 | neg_mask = neg_mask.view(-1, neg_mask.shape[-1]) |
| 39 | |
| 40 | pos_outputs = self(pos_ids, attention_mask=pos_mask, labels=torch.ones(pos_ids.shape[0], dtype=torch.uint8).to(pos_ids.get_device())) |
| 41 | neg_outputs = self(neg_ids, attention_mask=neg_mask, labels=torch.zeros(neg_ids.shape[0], dtype=torch.uint8).to(neg_ids.get_device())) |
| 42 | |
| 43 | loss_scale = 1.0 |
| 44 | loss = pos_outputs.loss + loss_scale * neg_outputs.loss |
| 45 | |
| 46 | pos_logits = pos_outputs.logits |
| 47 | pos_preds = torch.argmax(pos_logits, axis=1) |
| 48 | self.train_acc(pos_preds.cpu(), torch.ones(pos_ids.shape[0], dtype=torch.uint8).cpu()) |
| 49 | |
| 50 | neg_logits = neg_outputs.logits |
| 51 | neg_preds = torch.argmax(neg_logits, axis=1) |
| 52 | self.train_acc(neg_preds.cpu(), torch.zeros(neg_ids.shape[0], dtype=torch.uint8).cpu()) |
| 53 | |
| 54 | |
| 55 | return {'loss': loss} |
| 56 | |
| 57 | def validation_step(self, batch, batch_idx): |
| 58 | pos_ids, pos_mask, neg_ids, neg_mask = batch |
| 59 | |
| 60 | neg_ids = neg_ids.view(-1, neg_ids.shape[-1]) |
| 61 | neg_mask = neg_mask.view(-1, neg_mask.shape[-1]) |
| 62 | |
| 63 | pos_outputs = self(pos_ids, attention_mask=pos_mask, labels=torch.ones(pos_ids.shape[0], dtype=torch.uint8).to(pos_ids.get_device())) |
| 64 | neg_outputs = self(neg_ids, attention_mask=neg_mask, labels=torch.zeros(neg_ids.shape[0], dtype=torch.uint8).to(neg_ids.get_device())) |
| 65 | |
| 66 | loss_scale = 1.0 |
| 67 | loss = pos_outputs.loss + loss_scale * neg_outputs.loss |
| 68 | |
| 69 | pos_logits = pos_outputs.logits |
| 70 | pos_preds = torch.argmax(pos_logits, axis=1) |
| 71 | self.val_acc(pos_preds.cpu(), torch.ones(pos_ids.shape[0], dtype=torch.uint8).cpu()) |
nothing calls this directly
no outgoing calls
no test coverage detected