Evaluate the model on the eval dataset for each flag and return losses.
(model, eval_dataloader, flags)
| 22 | return {"input_ids": input_ids, "attention_mask": attention_mask, "labels": labels, "flag": flag} |
| 23 | |
| 24 | def evaluate_model(model, eval_dataloader, flags): |
| 25 | """Evaluate the model on the eval dataset for each flag and return losses.""" |
| 26 | model.eval() |
| 27 | eval_losses = {flag: 0.0 for flag in flags} |
| 28 | num_batches = len(eval_dataloader) |
| 29 | |
| 30 | with torch.no_grad(): |
| 31 | for flag in flags: |
| 32 | total_loss = 0.0 |
| 33 | for batch in eval_dataloader: |
| 34 | input_ids = batch["input_ids"].to(model.device) |
| 35 | attention_mask = batch["attention_mask"].to(model.device) |
| 36 | labels = batch["labels"].to(model.device) |
| 37 | |
| 38 | # Configure the subnetwork for the flag |
| 39 | model.configure_subnetwork(flag) |
| 40 | |
| 41 | # Forward pass |
| 42 | outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels) |
| 43 | total_loss += outputs.loss.item() |
| 44 | |
| 45 | eval_losses[flag] = total_loss / num_batches |
| 46 | |
| 47 | model.train() |
| 48 | return eval_losses |
| 49 | |
| 50 | if __name__ == "__main__": |
| 51 | # Load tokenizer |
no test coverage detected